我有一个对象数组,每个对象的属性:cow
设置为false
或true
:
animals = [
{
id: 1,
cow: true
},
{
id: 2,
cow: true
},
{
id: 3,
cow: true
},
{
id: 4,
cow: false
},
{
id: 5,
cow: false
}
]
我需要选择通过条件的数组的所有成员,而无需遍历数组的每个元素。
有可能吗?
我尝试过:
notCows = animals.reject { |a| !a[:cow] }
notCows = animals[0, 1, 2]
不起作用。
答案 0 :(得分:1)
不,这是不可能的。为了找到满足特定条件的所有元素,您需要查看所有元素以查看它们是否满足该条件。从逻辑上讲,不对集合的所有元素进行迭代就不可能找到集合的所有元素。
答案 1 :(得分:0)
您快到了,请使用Enumerable#select
(顺便说一句,它会扫描集合的所有成员):
animals.select { |animal| animal[:cow] }
#=> [{:id=>1, :cow=>true}, {:id=>2, :cow=>true}, {:id=>3, :cow=>true}]
或相反:
animals.select { |animal| !animal[:cow] }
#=> [{:id=>4, :cow=>false}, {:id=>5, :cow=>false}]
返回的结果仍然是Ruby对象:哈希数组。
您也可以按状态(Enumerable#group_by
)分组:
animals.group_by { |a| a[:cow] }
#=> {true=>[{:id=>1, :cow=>true}, {:id=>2, :cow=>true}, {:id=>3, :cow=>true}], false=>[{:id=>4, :cow=>false}, {:id=>5, :cow=>false}]}