How to find a hash key containing a matching value

后端 未结 10 691
走了就别回头了
走了就别回头了 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.

    0 讨论(0)
  • 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.

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

    From the docs:

    • (Object?) detect(ifnone = nil) {|obj| ... }
    • (Object?) find(ifnone = nil) {|obj| ... }
    • (Object) detect(ifnone = nil)
    • (Object) find(ifnone = nil)

    Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil otherwise.

    If no block is given, an enumerator is returned instead.

    (1..10).detect  {|i| i % 5 == 0 and i % 7 == 0 }   #=> nil
    (1..100).detect {|i| i % 5 == 0 and i % 7 == 0 }   #=> 35
    

    This worked for me:

    clients.detect{|client| client.last['client_id'] == '2180' } #=> ["orange", {"client_id"=>"2180"}] 
    
    clients.detect{|client| client.last['client_id'] == '999999' } #=> nil 
    

    See: http://rubydoc.info/stdlib/core/1.9.2/Enumerable#find-instance_method

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

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

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

    The best way to find the key for a particular value is to use key method that is available for a hash....

    gender = {"MALE" => 1, "FEMALE" => 2}
    gender.key(1) #=> MALE
    

    I hope it solves your problem...

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

    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"})
    
    0 讨论(0)
提交回复
热议问题