anyavacy anyavacy - 3 months ago 6
Ruby Question

Making a deep hash from an array of elements in Ruby

I have an array eg.

arr = [:a, :b, :c]
and i would like to make a hash from it in the form of

[{:a => [{:b => [:c] } ] } ]

mwp mwp
Answer

Quick and dirty:

[{ arr.shift => [{ arr.shift => [arr.shift] }] }]

To Cary's point, this is a little less dirty:

[{ arr[0] => [{ arr[1] => [arr[2]] }] }]

Or:

enum = arr.each
[{ enum.next => [{ enum.next => [enum.next] }] }]

If you're looking for something a little more flexible, here's a recursive method that does it:

def nest(arr)
  head, *tail = arr
  return [head] if tail.empty?
  [{ head => nest(tail) }]
end

nest([:a, :b, :c]) # => [{:a=>[{:b=>[:c]}]}]