自動建立深雜湊

雜湊具有請求但不存在的鍵的預設值(nil):

a = {}
p a[ :b ] # => nil 

建立新雜湊時,可以指定預設值:

b = Hash.new 'puppy'
p b[ :b ]            # => 'puppy'

Hash.new 還有一個塊,它允許你自動建立巢狀的雜湊,比如 Perl 的自動修改行為或者 mkdir -p

# h is the hash you're creating, and k the key.
#
hash = Hash.new { |h, k| h[k] = Hash.new &h.default_proc }
hash[ :a ][ :b ][ :c ] = 3

p hash # => { a: { b: { c: 3 } } }