How to find a hash key containing a matching value

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

    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.

    0 讨论(0)
  • 2020-12-04 05:58

    try this:

    clients.find{|key,value| value["client_id"] == "2178"}.first
    
    0 讨论(0)
  • 2020-12-04 06:00

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

    0 讨论(0)
  • 2020-12-04 06:00

    Heres an easy way to do find the keys of a given value:

        clients = {
          "yellow"=>{"client_id"=>"2178"}, 
          "orange"=>{"client_id"=>"2180"}, 
          "red"=>{"client_id"=>"2179"}, 
          "blue"=>{"client_id"=>"2181"}
        }
    
        p clients.rassoc("client_id"=>"2180")
    

    ...and to find the value of a given key:

        p clients.assoc("orange") 
    

    it will give you the key-value pair.

    0 讨论(0)
提交回复
热议问题