如果要构建一个多维的hash表
a = {}
a[1][2] = 2
会出现如下错误:
NoMethodError: undefined method `[]' for 2015-09-02 03:16:21 +0000:Time
错误的原因在于:
a 没有[][]方法,或者说,方法[]=返回的结果不是一个Hash,无法继续进行赋值。
构建方法
deep_hash = Hash.new { |h,k| h[k] = Hash.new(&h.default_proc) };
这样就建立一个递归的hash.
deep_hash[:a][:b][:c] = "weee!";
deep_hash
# => {:a=>{:b=>{:c=>"weee!"}}}
###原理
new {|hash, key| block } → new_hash
Returns a new, empty hash. If this hash is subsequently accessed by a key that doesn't correspond to a hash entry, the value returned depends on the style of new used to create the hash. In the first form, the access returns nil. If obj is specified, this single object will be used for all default values. If a block is specified, it will be called with the hash object and the key, and should return the default value. It is the block's responsibility to store the value in the hash if required.
在初始值里面的block有一个特点,会在没有key的时候会执行。如:
h = Hash.new { Time.now}
p h #是空表
a = h[:a] #表示是具体的时间
在上述递归Hash表中,default_proc 就是一个递归的block: { |h,k| h[k] = Hash.new(&h.default_proc) }会不断的产生新Hash,从而实现Hash的递归。