Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a value exists in an array of hashes

Tags:

arrays

ruby

People also ask

How do you find if an element exists in an array in Ruby?

This is another way to do this: use the Array#index method. It returns the index of the first occurrence of the element in the array. This returns the index of the first word in the array that contains the letter 'o'. index still iterates over the array, it just returns the value of the element.

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.

Is an array a hash?

With arrays, the key is an integer, whereas hashes support any object as a key. Both arrays and hashes grow as needed to hold new elements. It's more efficient to access array elements, but hashes provide more flexibility.


array_of_hashes.any? {|h| h[:a] == 11}

You did ask for a boolean result in the OQ, but if you really want the hash element itself do:

array_of_hashes.detect {  |h| h[:a] == 11 }

If you want the result really fast you could group the original object and then get the result with a single hash lookup:

t = array_of_hashes.group_by { |x| x[:a] }
t[11]