Hello.
I need to transform ["a", "b", "c", "d"]
to {:a => {:b => {:c => "d" }}}
?
Any ideas ?
Thanks
Hello.
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?
funny
ruby-1.8.7-p174 > ["a", "b", "c", "d"].reverse.inject{|hash,item| {item.to_sym => hash}}
=> {:a=>{:b=>{:c=>"d"}}}
If 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"}}}}}
I figured it out with help on IRC.
x = {}; a[0..-3].inject(x) { |h,k| h[k.to_sym] = {} }[a[-2].to_sym] = a[-1]; x
Second way with recursive (better)
def nest(a)
if a.size == 2
{ a[0] => a[1] }
else
{ a[0] => nest(a[1..-1]) }
end
end