首页 > 解决方案 > 如何检查哈希键是否与数组中的值匹配

问题描述

我有:

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"}]

标签: arraysrubyhash

解决方案


只需要稍作改动:

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

请参阅哈希#select

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


推荐阅读