如何在哈希中通过散列值在散列数组中进行search?

我有一个哈希数组,@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 

我怎样才能search这个数组,并返回一个块返回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