Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array select with multiple conditions ruby

Tags:

arrays

ruby

I can do:

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

What if I am given an unknown amount of colors and I want to select them all? i.e.

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

I've been working on a mess of code that creates several temporary arrays and then merges or flattens them into one, but I'm really unhappy with it.

like image 354
Ryan Florence Avatar asked Dec 18 '09 06:12

Ryan Florence


1 Answers

Try this:

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

You might also want to consider this instead, for in-place changes:

@items.reject! { |i| !colors.include?(i.color) }
like image 65
Alex Reisner Avatar answered Oct 25 '22 04:10

Alex Reisner