How to find a hash key containing a matching value

后端 未结 10 729
走了就别回头了
走了就别回头了 2020-12-04 05:24

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 cli

10条回答
  •  死守一世寂寞
    2020-12-04 05:34

    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.

提交回复
热议问题