How to check if specific value is present in a hash?

73,471

Solution 1

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.

Solution 2

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

Solution 3

Hash.has_value? and Hash.key.

Solution 4

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

Solution 5

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)
Share:
73,471
tyronegcarter
Author by

tyronegcarter

Updated on December 14, 2020

Comments

  • tyronegcarter
    tyronegcarter over 3 years

    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?