数组选择获取true和false数组?

时间:2014-01-27 15:03:22

标签: ruby arrays

我知道我可以轻松搞定:

array = [45, 89, 23, 11, 102, 95]
lower_than_50 = array.select{ |n| n<50}
greater_than_50 = array.select{ |n| !n<50}

但是,有一种方法(或优雅的方式)通过仅运行一次select来实现这一目标吗?

[lower_than_50, greater_than_50] = array.split_boolean{ |n| n<50}

2 个答案:

答案 0 :(得分:9)

over, under_or_equal = [45, 89, 23, 11, 102, 95].partition{|x| x>50 }

或者简单地说:

result = array.partition{|x| x>50 }
p result #=> [[89, 102, 95], [45, 23, 11]]

如果您希望将结果作为一个包含两个子数组的数组。

编辑:作为奖励,如果你有两个以上的选择并希望分割数字,你可以采用以下方式:

my_custom_grouping = -> x do
  case x
    when 1..50   then :small
    when 51..100 then :large
    else              :unclassified
  end
end

p [-1,2,40,70,120].group_by(&my_custom_grouping) #=> {:unclassified=>[-1, 120], :small=>[2, 40], :large=>[70]}

答案 1 :(得分:0)

上面的答案是现货!

以下是两个以上分区的一般解决方案(例如:<20, <50, >=50):

arr = [45, 89, 23, 11, 102, 95]
arr.group_by { |i| i < 20 ? 'a' : i < 50 ? 'b' : 'c' }.sort.map(&:last)
=> [[11], [45, 23], [89, 102, 95]]

如果您按块(或任何数学上可计算的索引,例如modulo)进行分组,这可能非常有用:

arr.group_by { |i| i / 50 }.sort.map(&:last)
=> [[45, 23, 11], [89, 95], [102]]