From: Glenn Ritz Date: 2010-03-09T22:05:54+09:00 Subject: Re: Flatten out Hash Jean G. wrote: > On Tue, Mar 9, 2010 at 8:31 PM, 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]] >> > > My method: > > hash = {"a"=>{"b"=>{"c"=>1}, "b2"=>{"c2"=>2}}} > array = [] > > 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: {"a"=>{"b"=>{"c"=>1}, "b2"=>{"c2"=> {"d2" => 2}}}} -- Posted via http://www.ruby-forum.com/.