我有一个哈希数组,@fathers。
a_father = { "father" => "Bob", "age" => 40 } @fathers << a_father a_father = { "father" => "David", "age" => 32 } @fathers << a_father a_father = { "father" => "Batman", "age" => 50 } @fathers << a_father
如何搜索此数组并返回一个块返回 true 的哈希数组?
例如:
@fathers.some_method("age" > 35) #=> array containing the hashes of bob and batman
谢谢。
您正在寻找Enumerable#select(也称为find_all):
find_all
@fathers.select {|father| father["age"] > 35 } # => [ { "age" => 40, "father" => "Bob" }, # { "age" => 50, "father" => "Batman" } ]
根据文档,它“返回一个数组,其中包含 [可枚举,在这种情况下@fathers] 的所有元素,其中块不为假。”
@fathers