How do I loop over a hash of hashes?
You'll want to recurse through the hash, here's a recursive method:
def ihash(h)
h.each_pair do |k,v|
if v.is_a?(Hash)
puts "key: #{k} recursing..."
ihash(v)
else
# MODIFY HERE! Look for what you want to find in the hash here
puts "key: #{k} value: #{v}"
end
end
end
You can Then take any hash and pass it in:
h = {
"x" => "a",
"y" => {
"y1" => {
"y2" => "final"
},
"yy1" => "hello"
}
}
ihash(h)
I little improved Travis's answer, how about this gist:
https://gist.github.com/kjakub/be17d9439359d14e6f86
class Hash
def nested_each_pair
self.each_pair do |k,v|
if v.is_a?(Hash)
v.nested_each_pair {|k,v| yield k,v}
else
yield(k,v)
end
end
end
end
{"root"=>{:a=>"tom", :b=>{:c => 1, :x => 2}}}.nested_each_pair{|k,v|
puts k
puts v
}
Value is a Hash to so you need iterate on it or you can get only values:-
h.each do |key, value|
puts key
value.each do |k,v|
puts k
puts v
end
end
or
h.each do |key, value|
puts key
value.values.each do |v|
puts v
end
end