我知道我可以很容易地得到这个:
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}
最佳答案
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]}
关于ruby - array select获取true和false数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21384170/