How to Check If Specific Value Is Present in a Hash?

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 Answers

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.

1

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? }
2

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

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)

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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest