32
votes

I'm using Rails and I have a hash object. I want to search the hash for a specific value. I don't know the keys associated with that value.

How do I check if a specific value is present in a hash? Also, how do I find the key associated with that specific value?

8

8 Answers

64
votes

Hash includes Enumerable, so you can use the many methods on that module to traverse the hash. It also has this handy method:

hash.has_value?(value_you_seek)

To find the key associated with that value:

hash.key(value_you_seek)

This API documentation for Ruby (1.9.2) should be helpful.

8
votes

The simplest way to check multiple values are present in a hash is:

h = { a: :b, c: :d }
h.values_at(:a, :c).all? #=> true
h.values_at(:a, :x).all? #=> false

In case you need to check also on blank values in Rails with ActiveSupport:

h.values_at(:a, :c).all?(&:present?)

or

h.values_at(:a, :c).none?(&:blank?)

The same in Ruby without ActiveSupport could be done by passing a block:

h.values_at(:a, :c).all? { |i| i && !i.empty? }
4
votes

Imagine you have the following Array of hashes

available_sports = [{name:'baseball', label:'MLB Baseball'},{name:'tackle_football', label:'NFL Football'}]

Doing something like this will do the trick

available_sports.any? {|h| h['name'] == 'basketball'}

=> false


available_sports.any? {|h| h['name'] == 'tackle_football'}

=> true

1
votes

The class Hash has the select method which will return a new hash of entries for which the block is true;

h = { "a" => 100, "b" => 200, "c" => 300 }
h.select {|k,v| v == 200}  #=> {"b" => 200}

This way you'll search by value, and get your key!

1
votes

While Hash#has_key? works but, as Matz wrote here, it has been deprecated in favour of Hash#key?.

Hash's key? method tells you whether a given key is present or not.

hash.key?(:some_key)
0
votes

If you do hash.values, you now have an array.

On arrays you can utilize the Enumerable search method include?

hash.values.include?(value_you_seek)
-2
votes

An even shorter version that you could use would be hash.values