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

时间:2023-01-01 12:42:41

I have an array of hashes, @fathers.

我有一组散列,@ dad。

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 

How can I search this array and return an array of hashes for which a block returns true?

如何搜索该数组并返回块返回为true的散列数组?

For example:

例如:

@fathers.some_method("age" > 35) #=> array containing the hashes of bob and batman

Thanks.

谢谢。

3 个解决方案

#1


359  

You're looking for Enumerable#select (also called find_all):

您正在寻找可枚举#select(也称为find_all):

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

Per the documentation, it "returns an array containing all elements of [the enumerable, in this case @fathers] for which block is not false."

根据文档,它“返回一个数组,该数组包含[enumerable,在本例中为@father]的所有元素,该元素的block不是false。”

#2


171  

this will return first match

这将返回第一场比赛

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

#3


20  

if your array looks like

如果你的数组是这样的

array = [
 {:name => "Hitesh" , :age => 27 , :place => "xyz"} ,
 {:name => "John" , :age => 26 , :place => "xtz"} ,
 {:name => "Anil" , :age => 26 , :place => "xsz"} 
]

And you Want To know if some value is already present in your array. Use Find Method

你想知道数组中是否已经存在某个值。使用Find方法

array.find {|x| x[:name] == "Hitesh"}

This will return object if Hitesh is present in name otherwise return nil

如果Hitesh在名称中出现,这将返回对象,否则返回nil

#1


359  

You're looking for Enumerable#select (also called find_all):

您正在寻找可枚举#select(也称为find_all):

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

Per the documentation, it "returns an array containing all elements of [the enumerable, in this case @fathers] for which block is not false."

根据文档,它“返回一个数组,该数组包含[enumerable,在本例中为@father]的所有元素,该元素的block不是false。”

#2


171  

this will return first match

这将返回第一场比赛

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

#3


20  

if your array looks like

如果你的数组是这样的

array = [
 {:name => "Hitesh" , :age => 27 , :place => "xyz"} ,
 {:name => "John" , :age => 26 , :place => "xtz"} ,
 {:name => "Anil" , :age => 26 , :place => "xsz"} 
]

And you Want To know if some value is already present in your array. Use Find Method

你想知道数组中是否已经存在某个值。使用Find方法

array.find {|x| x[:name] == "Hitesh"}

This will return object if Hitesh is present in name otherwise return nil

如果Hitesh在名称中出现,这将返回对象,否则返回nil