Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
  end
end

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]
  else
    hash[values.shift] = do_nesting(values, {})
  end

  return hash
end
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading