Ruby Hashes: Getting Deep
A neat way to test for values deep in the heart of a Hash.
= self
Array(key_array).each do |key|
value = value.fetch(key, nil)
end
value
rescue NoMethodError
nil
end
end
# Examples
h = {1 => {2 => {3 => 4}}}
h.deep_value(1) #=> {2 => {3 => 4}}
h.deep_value([1,2]) #=> {3 => 4}
h.deep_value([1,2,3,4]) #=> nil
h = {"farm" => {"animals" => ['sheep','pigs']},
"people" => {"farmers" => ['bill','joe'],
"children" => 'tommy'
}
}
h.deep_value(["farm","animals"]) #=> ['sheep','pigs']
h.deep_value(["farm","animals","edible"]) #=> nil
h.deep_value(["farm","people","farmers"]) #=> ['bill','joe']
h.deep_value(["farm","city folk"]) #=> nil
value