"Bob", "age" => 40 } @fathers "David", "age" => 32 } -6ren">
gpt4 book ai didi

ruby - 如何在 ruby​​ 中通过哈希值在哈希数组中进行搜索?

转载 作者:数据小太阳 更新时间:2023-10-29 06:16:32 26 4
gpt4 key购买 nike

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

我如何搜索这个数组并返回一个 block 返回 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] 的所有元素,其中 block 不是假的。”

关于ruby - 如何在 ruby​​ 中通过哈希值在哈希数组中进行搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2244915/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com