我有一系列哈希,@ 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。”
这将返回第一个匹配项
@fathers.detect {|f| f["age"] > 35 }
如果您的数组看起来像
array = [
{:name => "Hitesh" , :age => 27 , :place => "xyz"} ,
{:name => "John" , :age => 26 , :place => "xtz"} ,
{:name => "Anil" , :age => 26 , :place => "xsz"}
]
您想知道数组中是否已经存在某些值。使用查找方法
array.find {|x| x[:name] == "Hitesh"}
如果名称中包含Hitesh,则返回对象,否则返回nil