Convert array into nested hash for each element

I have an array of strings like this, each string is separated by comma. They can be in any order. I would like to build a nested hash out of it. If an item already exists, then subsequent elements should be nested. Example:

["a", "a,b", "d", "d,e", "d,e,f", "a,b,foobar"]

I want the output to be –

    a => {
      b => foobar
    d => {
      e => f

I was thinking to iterate over each element, then split it on , and add to a temporary Hash in some recursive way, but I can’t figure out how to get them nested.

>Solution :

First, a function to loop through the array and split those strings into an array which is much easier to work with.

def nest_array(array)
  return array.each_with_object({}) do |string, hash|
    values = string.split(/,/)

    do_nesting(values, hash)

Then a recursive function to deal with each individual entry. ['a'] becomes { a => nil }, ['a', 'b'] becomes { a => 'b' } and ['a', 'b', 'c'] recurses to make a new hash from ['b', 'c'].

def do_nesting(values, hash)
  if values.size <= 2
    hash[values[0]] = values[1]
    hash[values.shift] = do_nesting(values, {})

  return hash

Leave a Reply