Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if a hash has any of a number of keys

Tags:

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?

like image 243
Trevor Nowak Avatar asked Jan 20 '11 05:01

Trevor Nowak


People also ask

How do you check if a hash contains a key?

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.

Can a hash key be a number?

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

How do you know if something is a hash?

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 .


2 Answers

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.

like image 200
vonconrad Avatar answered Sep 29 '22 10:09

vonconrad


keys.any? { |i| hash.has_key? i } 
like image 38
Nakilon Avatar answered Sep 29 '22 10:09

Nakilon