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?
We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.
An explanation, why there are no examples with integers as Hash-keys. Hash-keys have (most of the times) a meaning. It may be an attribute name and its value (e.g. :color => 'red' ...). When you have an integer as a key, your semantic may be 'first, second ...' (1).
Overview. A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .
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.
keys.any? { |i| hash.has_key? i }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With