Selecting an array with multiple ruby ​​conditions

I can do:

@items = @items.select {|i| i.color == 'blue'} @items = @items.select {|i| i.color == 'blue' || i.color == 'red'} 

What if they give me an unknown number of colors and I want to select all of them? i.e.

 ['red','blue','green','purple'] # or ['blue','red'] 

I worked on a mess of code that creates several temporary arrays and then merges or aligns them into one, but I'm really not happy with it.

+7
arrays ruby
source share
2 answers

Try the following:

 colors = ['red','blue','green','purple'] @items = @items.select { |i| colors.include?(i.color) } 

You might also want to consider this instead of changes in place:

 @items.reject! { |i| !colors.include?(i.color) } 
+18
source share

Not sure if I fully understand your question, but will I work for you?

 colors_array = ['blue','red','whatever'] @items = @items.select {|i| colors_array.include?(i)} 
+1
source share

All Articles