简体   繁体   中英

How to search an array of hashes for the name of the hash containing a certain key-value pair? (Ruby)

I've got something like this:

array = [
  hash1 = {"marco"=>"polo", "girth"=>"skinny", "onion"=>true},
  hash2 = {"darco"=>"johnson", "girth"=>"wide", "onion"=>false},
  hash3 = {"flarco"=>"kiwi", "birth"=>"noble", "onion"=>false}
]

where one and only one onion is true at any given time.

I want an expression or function to return the name of the variable (ie hash1 , hash2 ) that holds the hash whose onion is currently true . How can I do that?

This is impossible. An object doesn't know about variables which reference it.

Similar effect can be achieved by replacing array with hash and making :hash1 , :hash2 and :hash3 keys.

Assuming we've got hash variable:

hash.keys.select{|key| hash[key]['onion']}

But if you relax the requirements a bit by allowing colons : instead of = signs:

array = [
  hash1: {"marco"=>"polo", "girth"=>"skinny", "onion"=>true},
  hash2: {"darco"=>"johnson", "girth"=>"wide", "onion"=>false},
  hash3: {"flarco"=>"kiwi", "birth"=>"noble", "onion"=>false}
]

We could work with that:

-> *_, **p { p.find { |_, v| v["onion"] }.first }.( *array )

Okay as you asked in the comment section of the post made by @Jörg W Mittag - Is there a way to return a certain key from the hash in array whose onion is true (not onion's key, though)? . Yes it is possible as I have shown below:

Here I considered one input array,where more than one Hash present,which are having true value for the key onion . Now to handle this situation enum#find_all will be needed.

array = [
  {"marco"=>"polo", "girth"=>"skinny", "onion"=>true},
 {"darco"=>"johnson", "girth"=>"wide", "onion"=>true},
  {"flarco"=>"kiwi", "birth"=>"noble", "onion"=>false}
]

array.find_all{|i| i["onion"]== true}.map{|i| i.keys[0]}
#>>["marco", "darco"]

As per the input array of OP , enum#find would work.

array = [
  {"marco"=>"polo", "girth"=>"skinny", "onion"=>true},
 {"darco"=>"johnson", "girth"=>"wide", "onion"=>false},
  {"flarco"=>"kiwi", "birth"=>"noble", "onion"=>false}
]

array.find{|i| i["onion"] }.keys[0]
# => "marco"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM