我有一系列哈希,@ 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):

@fathers.select {|father| father["age"] > 35 }
# => [ { "age" => 40, "father" => "Bob" },
#      { "age" => 50, "father" => "Batman" } ]

根据文档,它“返回一个数组,该数组包含[不可枚举,在这种情况下为@fathers]的所有元素,对于这些元素,块不是false。”

10-01 07:47