测试一个散列是否有多个键 [英] Testing if a hash has any of a number of keys
本文介绍了测试一个散列是否有多个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有更好的方法来测试一个散列是否有数组中的任何键。我想用这样的东西:
keys =%w [k1 k2 k5 k6]
none = true如果hash.key?(键)
或者我将不得不循环?
解决方案
无需循环:
(hash.keys& keys).any? #=> true
解释:
.keys
将散列中的所有键作为数组返回。 &
与两个数组相交,返回两个数组中存在的任何对象。最后, .any?
检查数组相交是否有任何值。
I was wondering if there was a better way to test if a hash has any keys from an array. I want to use it something like this:
keys = %w[k1 k2 k5 k6]
none = true if hash.key?(keys)
Or am I going to have to loop this?
解决方案
No need to loop:
(hash.keys & keys).any? # => true
Explanation:
.keys
returns all keys in a hash as an array. &
intersects two arrays, returning any objects that exists in both arrays. Finally, .any?
checks if the array intersect has any values.
这篇关于测试一个散列是否有多个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文