jfnietom jfnietom - 5 months ago 9
Ruby Question

Generate a tree from string split

I have an array of strings

["ana_ola_una",
"ana_ola_ina",
"ana_asta",
"ana_ena_ola",
"ana_ena_cala",
"ana_ena_cina",
"ana_ena_cina_ula"]


I need to reformat it as a hash of hashes of hashes of ... to make it a tree. The expected result would be:

{ana:
{
ola: {
una: {},
ina: {}
},
asta: {},
ena: {
ola: {},
cala:{},
cina:
{
ula: {}
}
}
}
}

Answer
arr = %w|ana_ola_una
  ana_ola_ina
  ana_asta
  ana_ena_ola
  ana_ena_cala
  ana_ena_cina
  ana_ena_cina_ula|

result = arr.each_with_object({}) do |s, memo|
  s.split('_').inject(memo) do |deep, k|
    deep[k.to_sym] ||= {}
  end 
end