Automatically creating a Deep Hash
suggest changeA 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 } } }
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents