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

doc*_*nge 227 ruby arrays hash search

我有一系列哈希,@ 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 
Run Code Online (Sandbox Code Playgroud)

如何搜索此数组并返回一个块返回true的哈希数组?

例如:

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

谢谢.

Jor*_*ing 401

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

@fathers.select {|father| father["age"] > 35 }
# => [ { "age" => 40, "father" => "Bob" },
#      { "age" => 50, "father" => "Batman" } ]
Run Code Online (Sandbox Code Playgroud)

根据文档,它"返回一个数组,其中包含[可枚举的所有元素@fathers] ,在这种情况下,哪个块不是false."

  • 哦! 你是第一个!删除我的答案和+1. (20认同)
  • 作为一个注释,如果你只想找到一个(第一个),你可以使用`@fathers.find {| father | 父亲["年龄"]> 35}`而不是. (18认同)

Nav*_*eed 191

这将返回第一场比赛

@fathers.detect {|f| f["age"] > 35 }
Run Code Online (Sandbox Code Playgroud)

  • 您还可以使用`find`而不是`detect`来获得更易读的代码 (12认同)
  • 但是,`find`会让你感到困惑. (8认同)
  • 我比"#select"更喜欢这个 - 但一切都适用于你的用例.如果没有找到匹配,`#detect`将返回`nil`,而@ Jordan的答案中的`#select`将返回`[]`. (6认同)
  • `select`和`detect`不相同,`select`将横向整个数组,而`detect`将在找到第一个匹配后立即停止.如果您正在寻找ONE match`@fathers.select {| f | f ["age"]> 35} .first` vs`@fathers.detect {| f | f ["age"]> 35}`为了表现和可读性,我的选票是`detect` (5认同)

Hit*_*aut 32

如果您的阵列看起来像

array = [
 {:name => "Hitesh" , :age => 27 , :place => "xyz"} ,
 {:name => "John" , :age => 26 , :place => "xtz"} ,
 {:name => "Anil" , :age => 26 , :place => "xsz"} 
]
Run Code Online (Sandbox Code Playgroud)

并且您想知道您的阵列中是否已存在某些值.使用查找方法

array.find {|x| x[:name] == "Hitesh"}
Run Code Online (Sandbox Code Playgroud)

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

  • 您可以使用类似的东西。array.find {| x | x [:name] .downcase ==“ Hitesh” .downcase} (2认同)

ARK*_*ARK 7

(添加到以前的答案(希望对某人有帮助):)

年龄更简单,但在字符串的情况下并忽略大小写:

  • 只是为了验证是否存在:

@fathers.any? { |father| father[:name].casecmp("john") == 0 }应该适用于 start 中或字符串中任何位置的任何情况,即 for "John""john"or"JoHn"等​​等。

  • 要查找第一个实例/索引:

@fathers.find { |father| father[:name].casecmp("john") == 0 }

  • 要选择所有此类索引:

@fathers.select { |father| father[:name].casecmp("john") == 0 }