12

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.

2 Answers 2

25

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

1 Comment

Awesome, the second is perfect.
1

not sure I fully understand your question but would work for you?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.