Get the key of a hash by knowing only one item inside the value which is an array in Ruby -


i want able key called "needed key" string out of considering value of "known_value

hash = {   "needed key" => {     :key1 => ["know_value", "unknown_value"],      :key2 => ["stuff", "more_stuff"]   }   "otherhash" => {     :key1 => ["unknow_value", "unknown_value"],      :key2 => []   } } 

in short how able retreive "needed key" code if know "know_value". using "know_value" out of need "needed key".

thank help.

hopefully clear enough, otherwise please ask me clearer.

this way extract desired key efficient in sense avoids construction of temporary, intermediate arrays, such hash.keys, flatten, hash[key], , on.

target = "known_value" hash.each_key.find { |k| hash[k].each_value { |a| a.include?(target) } }   #=> "needed key" 

this assumes, of course, looking key satisfies requirement.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -