How to find a hash key containing a matching value

后端 未结 10 743
走了就别回头了
走了就别回头了 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:35

    Another approach I would try is by using #map

    clients.map{ |key, _| key if clients[key] == {"client_id"=>"2180"} }.compact 
    #=> ["orange"]
    

    This will return all occurences of given value. The underscore means that we don't need key's value to be carried around so that way it's not being assigned to a variable. The array will contain nils if the values doesn't match - that's why I put #compact at the end.

提交回复
热议问题