我如何通过ruby中的哈希值在哈希数组中搜索?

问题描述 投票:228回答:3

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

谢谢。

ruby search hash arrays
3个回答
404
投票

您正在寻找Enumerable#select(也称为find_all):

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

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


193
投票

这将返回第一个匹配项

@fathers.detect {|f| f["age"] > 35 }

33
投票

如果您的数组看起来像

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

© www.soinside.com 2019 - 2024. All rights reserved.