supersize supersize - 9 days ago 5
Ruby Question

Select from array with given substring value

I have an array which looks like this:

arr = ["value1", "value2 spot", "value3", "value4", "value5 spot", "value6"]


and I would like to select and return an array with all values which have the
spot
substring.

arr.select{|v| v == regex_here}


how would I be able to do this?

Answer

You could use grep method

 arr.grep(/spot/)
  => ["value2 spot", "value5 spot"] 

Other request you made

arr.group_by { |item| item.match(/spot/) != nil }
 => {false=>["value1", "value3", "value4", "value6"], true=>["value2 spot", "value5 spot"]}