How to find a hash key containing a matching value

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

提交回复
热议问题