【问题标题】:How to check if hash keys match value from array如何检查哈希键是否与数组中的值匹配
【发布时间】:2019-01-24 18:39:58
【问题描述】:

我有:

arr = ['test', 'testing', 'test123']
ht = {"test": "abc", "water": "wet", "testing": "fun"}

如何在ht 中选择键与arr 匹配的值?

ht_new = ht.select {|hashes| arr.include? hashes}
ht_new # => "{"test": "abc", "testing": "fun"}"

此外,我们如何从以下位置返回值:

arr = ["abc", "123"]
ht = [{"key": "abc", "value": "test"}, {"key": "123", "value": "money"}, {"key": "doremi", "value": "rain"}}]
output # => [{"key": "abc", "value": "test"}, {"key": "123", "value": "money"}]

【问题讨论】:

  • 您的代码ht_new = ht.select {|hashes| arr.include? hashes} 代表什么?是你失败的尝试吗?或者您是否声称它返回 {"test": "abc", "testing": "fun"},这是一个谎言,因为键值对与 arr 进行比较,此外,ht 中的任何键都不匹配 arr,除非您从字符串转换为符号?
  • 第二个 ht 不是有效的 Ruby 表达式。你的第二个问题也不清楚。

标签: arrays ruby hash


【解决方案1】:

只需要稍作改动:

ht.select { |k,_| arr.include? k.to_s }
  ##=> {:test=>"abc", :testing=>"fun"}

Hash#select

块变量_(一个有效的局部变量),它是键k的值,向读者表明它没有用于块计算。有些人更喜欢写 |k,_v| 或类似的东西。

【讨论】:

    【解决方案2】:

    一个选项是映射(Enumerable#maparr 中的键:

    arr.map.with_object({}) { |k, h| h[k] = ht[k.to_sym] }
    
    #=> {"test"=>"abc", "testing"=>"fun", "test123"=>nil}
    

    如果你想去掉带有nil 值的对:

    arr.map.with_object({}) { |k, h| h[k] = ht[k.to_sym] if ht[k.to_sym] }
    
    #=> {"test"=>"abc", "testing"=>"fun"}
    


    这是最后一个请求的选项:
    ht.select{ |h| h if h.values.any? { |v| arr.include? v} }
    # or
    arr.map { |e| ht.find { |h| h.values.any?{ |v| v == e } } }
    
    #=> [{:key=>"abc", :value=>"test"}, {:key=>"123", :value=>"money"}]
    

    【讨论】:

    • 在这里使用reduce 可能会更好,因为 OP 不想要在数组中找不到的键
    • @maxpleaner 谢谢我明白了。我添加了一种拒绝零值的方法。但我不知道如何使用reduce
    • 编辑附加请求的答案
    【解决方案3】:

    一个简单的方法是:

     ht.slice(*arr.map(&:to_sym))
    # => {:test => "abc", :testing => "fun"}
    

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 1970-01-01
      • 2018-06-14
      • 2012-06-12
      • 1970-01-01
      • 2011-02-15
      • 2017-04-28
      • 1970-01-01
      • 2013-11-16
      相关资源
      最近更新 更多