title: How do I flatten a nested hash, recursively, into an array of arrays with a specific format?
body: <p>I have a nested hash that looks something like this:</p>
  
  <pre><code>{
    'a' =&gt; {
      'b' =&gt; ['c'],
      'd' =&gt; {
        'e' =&gt; ['f'],
        'g' =&gt; ['h', 'i', 'j', 'k']
      },
      'l' =&gt; ['m', 'n', 'o', 'p']
    },
    'q' =&gt; {
      'r' =&gt; ['s']
    }
  }
  </code></pre>
  
  <p>The hash can have even more nesting, but the values of the last level are always arrays.</p>
  
  <p>I would like to "flatten" the hash into a format where I get a an array of arrays representing all keys and values that makes up an entire "path/branch" of the nested hash all they way from lowest level value to the top of the hash. So kind of like traversing up through the "tree" starting from the bottom while collecting keys and values on the way.</p>
  
  <p>The output of that for the particular hash should be:  </p>
  
  <pre><code>[
    ['a', 'b', 'c'],
    ['a', 'd', 'e', 'f'],
    ['a', 'd', 'g', 'h', 'i', 'j', 'k'],
    ['a', 'l', 'm', 'n', 'o', 'p'],
    ['q', 'r', 's']
  ]
  </code></pre>
  
  <p>I tried many different things, but nothing worked so far. Again keep in mind that more levels than these might occur, so the solution has to be generic.</p>
  
  <p><strong>Note:</strong> the order of the arrays and the order of the elements in them is not important.</p>
  
  <p>I did the following, but it's not really working:</p>
  
  <pre><code>tree_def = {
    'a' =&gt; {
      'b' =&gt; ['c'],
      'd' =&gt; {
        'e' =&gt; ['f'],
        'g' =&gt; ['h', 'i', 'j', 'k']
      },
      'l' =&gt; ['m', 'n', 'o', 'p']
    },
    'q' =&gt; {
      'r' =&gt; ['s']
    }
  }
  branches = [[]]
  
  collect_branches = lambda do |tree, current_branch|
    tree.each do |key, hash_or_values|
      current_branch.push(key)
      if hash_or_values.kind_of?(Hash)
        collect_branches.call(hash_or_values, branches.last)
      else # Reached lowest level in dependency tree (which is always an array)
        # Add a new branch
        branches.push(current_branch.clone)
        current_branch.push(*hash_or_values)
        current_branch = branches.last
      end
    end
  end
  
  collect_branches.call(tree_def, branches[0])
  
  branches #=&gt; wrong result
  </code></pre>