本文介绍了我如何散列的红宝石数组由哈希值进行搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有散列的数组,@fathers。

I have an array of hashes, @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?

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

例如:

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

感谢。

推荐答案

您正在寻找(也称为 find_all

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

每文档,它将返回一个包含所有元素的数组[可枚举,在这种情况下 @fathers ]对于该块不是假的。

这篇关于我如何散列的红宝石数组由哈希值进行搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 15:22