如何检查哈希键是否匹配数组中的值 [英] How to check if hash keys match value from array
本文介绍了如何检查哈希键是否匹配数组中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有:
arr = ['test', 'testing', 'test123']
ht = {"test": "abc", "water": "wet", "testing": "fun"}
如何在键与arr
匹配的ht
中选择值?
How can I select the values in ht
whose key matches arr
?
ht_new = ht.select {|hashes| arr.include? hashes}
ht_new # => "{"test": "abc", "testing": "fun"}"
此外,我们如何从以下位置返回值:
Additionally, how can we return values from:
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.select { |k,_| arr.include? k.to_s }
##=> {:test=>"abc", :testing=>"fun"}
请参见哈希#select .
块变量_
(有效的局部变量),它是键k
的值,向读者表示该变量未在块计算中使用.有些人更喜欢写|k,_v|
或类似的东西.
The block variable _
(a valid local variable), which is the value of key k
, signifies to the reader that it is not used in the block calculation. Some prefer writing that |k,_v|
, or some-such.
这篇关于如何检查哈希键是否匹配数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文