Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 605
tyronegcarter Avatar asked Jan 26 '12 00:01

tyronegcarter


People also ask

How do you check if a value exists in a hash Perl?

Perl | exists() Function The exists() function in Perl is used to check whether an element in an given array or hash exists or not. This function returns 1 if the desired element is present in the given array or hash else returns 0.

How do you get the key of a hash in Ruby?

Ruby | Hash key() functionHash#key() is a Hash class method which gives the key value corresponding to the value. If value doesn't exist then return nil.

How do you know if two hashes are equal?

Equality—Two hashes are equal if they each contain the same number of keys and if each key-value pair is equal to (according to Object#== ) the corresponding elements in the other hash. The orders of each hashes are not compared. Returns true if other is subset of hash.


2 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.

like image 147
rkb Avatar answered Oct 13 '22 16:10

rkb


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? } 
like image 34
Anton Orel Avatar answered Oct 13 '22 15:10

Anton Orel