代码之家  ›  专栏  ›  技术社区  ›  Ryan Florence

多条件数组选择Ruby

  •  9
  • Ryan Florence  · 技术社区  · 15 年前

    我能做到:

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

    如果给我一个未知数量的颜色,我想全部选择它们怎么办?即

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

    我一直在研究一堆代码,这些代码创建了几个临时数组,然后将它们合并或平展成一个数组,但我真的对它不满意。

    2 回复  |  直到 15 年前
        1
  •  20
  •   Alex Reisner    15 年前

    试试这个:

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

    您可能还需要考虑这一点,因为就地更改:

    @items.reject! { |i| !colors.include?(i.color) }
    
        2
  •  1
  •   Karmen Blake    15 年前

    我不确定我完全理解你的问题,但会为你工作吗?

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