Search code examples
ruby

How to find a hash key containing a matching value


Given I have the below clients hash, is there a quick ruby way (without having to write a multi-line script) to obtain the key given I want to match the client_id? E.g. How to get the key for client_id == "2180"?

clients = {
  "yellow"=>{"client_id"=>"2178"}, 
  "orange"=>{"client_id"=>"2180"}, 
  "red"=>{"client_id"=>"2179"}, 
  "blue"=>{"client_id"=>"2181"}
}

Solution

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