-1

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?

2
  • How about: .*\bspot\b.* Commented Nov 28, 2016 at 10:53
  • a, b = arr.partition {|s| s[/spot/]} then a returns true values, b returns false values. Commented Nov 28, 2016 at 13:36

2 Answers 2

3

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"]} 
Sign up to request clarification or add additional context in comments.

3 Comments

thanks, this works great! Can you also assist to get all values which don't have the substring spot seperately.
I updated my answer
Try partition too.
0

You can use

arr.select{ |i| i[/spot/] }
 => ["value2 spot", "value5 spot"] 

2 Comments

“should” is a wrong word here—the most proper solution would be to use grep.
@mudasobwa Okay cool

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.