Given a hash –
hash = {
1 => {"ID" => ["NUMBER", 11] },
2 => {"TITLE" => ["VARCHAR2", 5] },
3 => {"FIRST_NAME" => ["VARCHAR2", 50] },
4 => {"LAST_NAME" => ["VARCHAR2", 50] },
5 => {"BIRTH_DATE" => ["DATE", -2] }
}
and 2 input parameters – "FIRST_NAME" and ["VARCHAR2",50].
What is the most elegant way to do –
- check whether
"FIRST_NAME"exists as key of any nested hash. - And if it exists whether value of
hash[3]["FIRST_NAME"]is equal to second parameter i.e.["VARCHAR2",50]. - And if these 2 parameters match then return the key whose value is this nested hash i.e. 3 in this case
Currently I do the following –
array = hash.values.map {|h| h.to_a}.flatten(2)
puts hash.key(Hash["FIRST_NAME",["VARCHAR2",50]]) if !(index = array.index("FIRST_NAME")).nil? ? array[index+1] == ["VARCHAR2",50] : false # 3
You will find a lot of information in you check the
hash api.You could also write it as below actually because if it does not contain the key, it will never match and just go to the next occurence.
Your example only show hash with one pair, if there is more your need to do a new
eachonv.