I need to transform ["a", "b", "c", "d"] to {:a => {:b => {:c => "d" }}} ?
Any ideas ?
Thanks
I like it:
class Array
def to_weird_hash
length == 1 ? first : { first.to_sym => last(length - 1).to_weird_hash }
end
end
["a", "b", "c", "d"].to_weird_hash
What do you think?
from in both 1.8.7 and 1.9.2If you need to do it for exactly 4 elements, it's easy enought to just write it out (and quite readable too)
>> A=["a", "b", "c", "d"]
=> ["a", "b", "c", "d"]
>> {A[0].to_sym => {A[1].to_sym => {A[2].to_sym => A[3]}}}
=> {:a=>{:b=>{:c=>"d"}}}
Otherwise, this will work for variable length arrays
>> ["a", "b", "c", "d"].reverse.inject(){|a,e|{e.to_sym => a}}
=> {:a=>{:b=>{:c=>"d"}}}
>> ["a", "b", "c", "d", "e", "f"].reverse.inject(){|a,e|{e.to_sym => a}}
=> {:a=>{:b=>{:c=>{:d=>{:e=>"f"}}}}}
{:a => {:b => {:c => "d" }}}rather than{:a => :b, :c => :d}?