From: Brian Candler Date: 2010-03-09T22:15:58+09:00 Subject: Re: Flatten out Hash Glenn Ritz wrote: > Hi, > > I would like to take a nested hash that looks like this: > > {"a"=>{"b"=>{"c"=>1}, "b2"=>{"c2"=>2}}} > > and turn it into an array of 2 element arrays like this: > > [["a: b2: c2: ", 2], ["a: b: c: ", 1]] > > Is there a simple way to do this? I wrote a method that iterates > through the nested hashes recursively, but it's a bit cumbersome. I think that's the right way, if the nesting depth is variable. One example: 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}}} p h.to_enum(:flat_each).collect { |k,v| [k,v] } -- Posted via http://www.ruby-forum.com/.