Reputation: 3956
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?
Upvotes: 36
Views: 81578
Reputation: 8035
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
Upvotes: 4
Reputation: 576
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? }
Upvotes: 8
Reputation: 34023
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)
Upvotes: 1
Reputation: 3265
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)
Upvotes: 2
Reputation: 8657
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!
Upvotes: 1
Reputation: 3542
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.
Upvotes: 69