hash.keys.each do |k1|
hash[k1].keys.each do |k2|
hash[k1][k2].keys.each do |k3|
array << ["#{k1}: #{k2}: #{k3}:",hash[k1][k2][k3]]
end
end
end
Thanks, Jean.
It's a good solution. But it's dependent on there being 3 levels of
hashes. What if you didn't know how many levels of nesting there was
before executing the code? Suppose the hash looked like this instead:
Perhaps a better solution is to yield an array of keys (being the 'path'
to reach the end node), because then the caller can choose how to
combine them.
class Hash
def flat_each(prefix=[], &blk)
each do |k,v|
if v.is_a?(Hash)
v.flat_each(prefix+[k], &blk)
else
yield prefix+[k], v
end
end
end
end
require 'enumerator'
h = {"a"=>{"b"=>{"c"=>1}, "b2"=>{"c2"=>2}}}
h = {"a"=>{"b"=>{"c"=>1}, "b2"=>{"c2"=> {"d2" => 2}}}}
p h.to_enum(:flat_each).collect { |k,v| [k.join(": "),v] }
h.flat_each do |k,v|
puts "#{k.join("/")} => #{v}"
end
hash.keys.each do |k1|
hash[k1].keys.each do |k2|
hash[k1][k2].keys.each do |k3|
array << ["#{k1}: #{k2}: #{k3}:",hash[k1][k2][k3]]
end
end
end
Thanks, Jean.
It's a good solution. But it's dependent on there being 3 levels of
hashes. What if you didn't know how many levels of nesting there was
before executing the code? Suppose the hash looked like this instead: