Ruby grep - array search for parts of a string

I am new to Ruby and a bit confused by the grep command in this block of code. I am trying to collect all the mailbox names through Net :: IMAP and then check them for the mailbox argument. The mailbox name will probably include only part of the argument. For example, someone might enter โ€œSentโ€ as a mailbox, but many times the name of the mailbox will be โ€œINBOX.Sentโ€.

class ExamineMail def initialize(user, domain, pass, box) @username = user @domain = domain @pass = pass @mailbox = box end def login() @imap = Net::IMAP.new("mail." + @domain) @imap.authenticate('LOGIN', @username + "@" + @domain, @pass) mailbox_array = @imap.list('','*').collect{ |mailbox| mailbox.name } #mailbox_array.any? { |w| @mailbox =~ /#{w}/ } mailbox_array.grep(/^@mailbox/) end end 

So, first I tried .any? but this does not return me the name of the actual mailbox. With .grep I can get a list of mailboxes when @mailbox = "INBOX" . However, when @mailbox = "Sent" it just returns [] .

Here is an example of one that works (using "INBOX"), and one that does not use (using "Sent"):

 #Get the list of inboxes mailbox_array = imap.list('','*').collect{ |mailbox| mailbox.name } => ["INBOX", "INBOX.Trash", "INBOX.Sent", "INBOX.Sent Messages", "INBOX.Junk", "INBOX.Drafts", "INBOX.Deleted Messages", "INBOX.Apple Mail To Do"] #Search for mailboxes including "Sent" >> mailbox_array.grep(/^Sent/) => [] #Search for "INBOX" >> mailbox_array.grep(/^INBOX/) => ["INBOX", "INBOX.Trash", "INBOX.Sent", "INBOX.Sent Messages", "INBOX.Junk", "INBOX.Drafts", "INBOX.Deleted Messages", "INBOX.Apple Mail To Do"] 

I think the problem is that "INBOX" is at the beginning of the lines in the array, but "Sent" is in the middle and after the period. Not sure how to fix it.

+6
source share
2 answers

Try:

 mailbox_array.grep(/Sent/) 

The ^ sign means search from the beginning of a line.

+12
source

The special regular expression character ^ matches only the beginning of a line, so maybe you want to match the word boundary ( \b ). Try the following:

 mailbox_array.grep(/\bSent\b/) 
+7
source

Source: https://habr.com/ru/post/909566/


All Articles