Trevor Nowak Trevor Nowak - 1 year ago 57
Ruby Question

Testing if a hash has any of a number of keys

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?

Answer Source

No need to loop:

(hash.keys & keys).any? # => true


.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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download