【问题标题】:How do I search within an array of hashes by hash values in ruby?如何通过 ruby​​ 中的哈希值在哈希数组中搜索?
【发布时间】:2011-01-15 17:44:34
【问题描述】:

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

例如:

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

谢谢。

【问题讨论】:

  • 这个问题很有帮助,但我一直想知道为什么需要一组@fathers :P

标签: ruby search hash arrays


【解决方案1】:

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

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

  • 只是为了验证存在:

@fathers.any? { |father| father[:name].casecmp("john") == 0 } 应该适用于开头的任何大小写或字符串中的任何位置,即"John""john""JoHn" 等等。

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

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

  • 要选择所有此类索引:

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

【讨论】:

    【解决方案2】:

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

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

    根据文档,它“返回一个数组,其中包含 [可枚举,在本例中为 @fathers] 的所有元素,其中块不为假。”

    【讨论】:

    • 哦!你是第一个!删除我的回答和 +1。
    • 请注意,如果您只想找到一个(第一个),您可以改用@fathers.find {|father| father["age"] &gt; 35 }
    • 是否可以返回在原始哈希数组中找到它的索引?
    • @IanWarner 是的。我建议查看 Enumerable 模块的文档。如果您仍然无法弄清楚,请发布一个新问题。
    • 我刚刚做了这个 index = ARRAY.index { | h | h[ :code ] == ARRAY[ "code" ] }
    【解决方案3】:

    如果你的数组看起来像

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

    并且您想知道您的数组中是否已经存在某些值。使用查找方法

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

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

    【讨论】:

    • 如果名字是小写的,比如"hitesh",它不会返回哈希值。在这种情况下,我们如何考虑单词大小写?
    • 你可以使用类似的东西。数组.find {|x| x[:name].downcase == "Hitesh".downcase }
    • @arjun array.any?{ |element| element[:name].casecmp("hitesh")==0 } 应该适用于开头的任何大小写或字符串中的任何地方,即"Hitesh""hitesh""hiTeSh"
    • 实际查看我的答案:stackoverflow.com/a/63375479/10313894
    • finddetect 方法的别名
    【解决方案4】:

    这将返回第一个匹配项

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

    【讨论】:

    • 我更喜欢这个而不是#select - 但一切都适合您的用例。如果找不到匹配项,#detect 将返回 nil,而 @Jordan 的答案中的 #select 将返回 []
    • 您也可以使用find 代替detect 以获得更易读的代码
    • 但是,find 在 Rails 中可能会让人感到困惑。
    • selectdetect 不一样,select 将遍历整个数组,而detect 将在找到第一个匹配项后立即停止。如果您正在寻找 ONE match @fathers.select {|f| f["age"] &gt; 35 }.first vs @fathers.detect {|f| f["age"] &gt; 35 } 以提高性能和可读性,我投票支持detect
    猜你喜欢
    • 2016-06-27
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多