2013-01-05 29 views
2

他們它創建水平的哈希乾淨的方式這是我現在做的創建具有3層嵌套,如果不存在

h = Hash.new { |h1, k1| h1[k1] = Hash.new { |h2, k2| h2[k2] = {} } } 

雖然它的工作原理,它看起來有點曖昧。也許有更好的方法來做同樣的事情?

回答

3
h = hash.new{ |h,k| h[k] = Hash.new(&h.default_proc) } 

然後你就可以反正你喜歡的分配,

h[:a][:b][:c][:d] = 3 

參考:ref

1

您可以像這樣遞歸創建一個。

def create n 
    return {} if n == 0 
    Hash.new {|h, k| h[k] = create(n - 1)} 
end 

h = create 3 
h[1][1][1] = 2 
p h[1][1][1]  # => 2 
p h[2][1][2]  # => {} 
h[2][1][2] = 3 
p h    # => {1=>{1=>{1=>2}}, 2=>{1=>{2=>3}}} 
1

您的代碼是正確的。你可以把它歸類:

class NestedHash < Hash 

    def initialize(depth) 
    self.default_proc = Proc.new {|h,k| h[k] = NestedHash.new(depth-1)} if depth && depth > 1 
    end 

end 

h = NestedHash.new(3)