Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a hash key containing a matching value

Tags:

ruby

People also ask

How do I find the hash key?

To find a hash key by it's value, i.e. reverse lookup, one can use Hash#key . It's available in Ruby 1.9+.

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.

What is hash key value pair?

A hash table is a type of data structure that stores key-value pairs. The key is sent to a hash function that performs arithmetic operations on it. The result (commonly called the hash value or hash) is the index of the key-value pair in the hash table.


Ruby 1.9 and greater:

hash.key(value) => key

Ruby 1.8:

You could use hash.index

hsh.index(value) => key

Returns the key for a given value. If not found, returns nil.

h = { "a" => 100, "b" => 200 }
h.index(200) #=> "b"
h.index(999) #=> nil

So to get "orange", you could just use:

clients.key({"client_id" => "2180"})

You could use Enumerable#select:

clients.select{|key, hash| hash["client_id"] == "2180" }
#=> [["orange", {"client_id"=>"2180"}]]

Note that the result will be an array of all the matching values, where each is an array of the key and value.


You can invert the hash. clients.invert["client_id"=>"2180"] returns "orange"


You could use hashname.key(valuename)

Or, an inversion may be in order. new_hash = hashname.invert will give you a new_hash that lets you do things more traditionally.


try this:

clients.find{|key,value| value["client_id"] == "2178"}.first

According to ruby doc http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-key key(value) is the method to find the key on the base of value.

ROLE = {"customer" => 1, "designer" => 2, "admin" => 100}
ROLE.key(2)

it will return the "designer".