Automatically creating a Deep Hash

suggest change

A hash returns a default for a key that has not been set (nil unless you choose another default):

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

When creating a hash, you can specify the default. The same object is returned for every missing key, so a mutable default is shared:

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

Hash.new also takes a block, which lets you create nested hashes on demand, as in Perl’s autovivification or 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 } } }

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents