如何通过 ruby​​ 中的哈希值在哈希数组中搜索? [英] How do I search within an array of hashes by hash values in ruby?

查看:43
本文介绍了如何通过 ruby​​ 中的哈希值在哈希数组中搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何搜索这个数组并返回一个哈希数组,其中一个块返回真值?

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

谢谢.

推荐答案

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

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

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

根据文档,它返回一个数组,其中包含 [enumerable,在本例中为 @fathers] 的所有元素,其中块不为 false."

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

这篇关于如何通过 ruby​​ 中的哈希值在哈希数组中搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆