开发者

Array select with multiple conditions 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 c开发者_如何学运维olors 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.


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) }


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)}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜