title: Transform deeply nested ruby hash
body: <p>I have a deeply nested Ruby hash which I need to transform into another hash. A Hash might have 0 or more children. <strong>Here's the input hash:</strong> </p>
  
  <pre><code>"{'id' =&gt; 'apple', 'children' =&gt; [{'id' =&gt; 'ipad', 'children' =&gt; [{'id' =&gt; 'ipadmini'}]},{'id' =&gt; 'ipadmini'}]}"
  </code></pre>
  
  <p><strong>output</strong></p>
  
  <pre><code>[{"ipad"=&gt;{"id"=&gt;"ipad", "paths"=&gt;[[{"id"=&gt;"apple"}, {"id"=&gt;"ipad"}]]}},
  {"ipadmini"=&gt;{"id"=&gt;"ipadmini", "paths"=&gt;[[{"id"=&gt;"ipad"}, {"id"=&gt;"ipadmini"}], [{"id"=&gt;"apple"}, {"id"=&gt;"ipad"}, {"id"=&gt;"ipadmini"}]]}}, {"apple"=&gt;{"id"=&gt;"apple", "paths"=&gt;[[{"id"=&gt;"apple"}]]}}]
  </code></pre>
  
  <p><strong>my code:</strong></p>
  
  <pre><code>def construct_concept(concept)
      h = {}
      c = Hash[*concept.to_a.first]
      c['paths'] = [[Hash[*concept.to_a.first]]]
      h[concept['id']] = c
      h
  end
  
  def parent_child_concepts(concepts)
      pc = {}
      pc[:parent] = Hash[*concepts.first]
      pc[:children] = concepts.values_at('children').flatten.map {|child| parent_child_concepts(child)} || []
      pc
  end
  
  def add_parent_child_paths(parent_hash,children_array)
      h = {}
      parent_hash.each do |parent_key,parent_value|
          h[parent_key] = parent_value
          children_array.each do |child|
              child.each do |k,v|
                  h[k] = v
                  h[k]['paths'].map {|path| path.unshift({'id' =&gt; parent_key})}
              end
          end
      end
      h
  end
  
  def build_concept_data(concepts)
      #concept {"id"=&gt;"apple", "children"=&gt;[{"id"=&gt;"ipad"}]}
      parsed_concepts = parent_child_concepts(concepts)
      parent = construct_concept(parsed_concepts[:parent])
      children = parsed_concepts[:children].each_with_object([]) {|child,accu| accu &lt;&lt; construct_concept(child)}
      concept_paths_data = add_parent_child_paths(parent,children)
  end
  </code></pre>