我需要转换["a", "b", "c", "d"]
为{:a => {:b => {:c => "d" }}}
?
有任何想法吗 ?
谢谢
有趣的
ruby-1.8.7-p174 > ["a", "b", "c", "d"].reverse.inject{|hash,item| {item.to_sym => hash}}
=> {:a=>{:b=>{:c=>"d"}}}
我喜欢:
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
你怎么看?
如果您需要针对 4 个元素执行此操作,只需将其写出来就很容易(而且可读性也很强)
>> 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"}}}
否则,这将适用于可变长度数组
>> ["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"}}}}}
我在 IRC 的帮助下想通了。
x = {}; a[0..-3].inject(x) { |h,k| h[k.to_sym] = {} }[a[-2].to_sym] = a[-1]; x
递归的第二种方式(更好)
def nest(a)
if a.size == 2
{ a[0] => a[1] }
else
{ a[0] => nest(a[1..-1]) }
end
end