From: Anton Scipio Date: 2013-06-05T01:00:22+09:00 Subject: Re: Create a nested structure from a CSV unsubscribe ________________________________________ From: Joel Pearson [lists@ruby-forum.com] Sent: 04 June 2013 16:43 To: ruby-talk ML Subject: Re: Create a nested structure from a CSV Bah, my brain hurts too much to write a recursive hashifier at the moment. Maybe this will help inspire you; I wrote something a while ago to do this the other way around: Turning a nested Hash into a 2D Array (although I still don't know how it works). h = { Part1: { Type1: { SubType1: 1, SubType2: 2, SubType3: 3 }, Type2: { SubType1: 4, SubType2: 5, SubType3: 6 } }, Part2: { Type1: { SubType1: 1, SubType2: 2, SubType3: 3 }, Type2: { SubType1: 4, SubType2: 5, SubType3: 6 } } } def convert_hash(h) _hash_to_a(h).each_slice(2).map { |a1,a2| a1 << a2.last } end def hash_to_a(h) h.map { |k,v| v.is_a?(Hash) ? _hash_to_a(v).map { |val| ([ k ] + [ val ]).flatten(1) } : [ k, v ] }.flatten(1) end require 'pp' pp convert_hash(h) [[:Part1, :Type1, :SubType1, 1], [:Part1, :Type1, :SubType2, 2], [:Part1, :Type1, :SubType3, 3], [:Part1, :Type2, :SubType1, 4], [:Part1, :Type2, :SubType2, 5], [:Part1, :Type2, :SubType3, 6], [:Part2, :Type1, :SubType1, 1], [:Part2, :Type1, :SubType2, 2], [:Part2, :Type1, :SubType3, 3], [:Part2, :Type2, :SubType1, 4], [:Part2, :Type2, :SubType2, 5], [:Part2, :Type2, :SubType3, 6]] -- Posted via http://www.ruby-forum.com/.