Testing if a hash has any of a number of keys

2019-01-17 07:18发布

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?

标签: ruby hash
2条回答
女痞
2楼-- · 2019-01-17 08:04
keys.any? { |i| hash.has_key? i }
查看更多
smile是对你的礼貌
3楼-- · 2019-01-17 08:23

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.

查看更多
登录 后发表回答