Ruby Language Hashes Automatically creating a Deep Hash

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Hash has a default value for keys that are requested but don't exist (nil):

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

When creating a new Hash, one can specify the default:

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

Hash.new also takes a block, which allows you to automatically create nested hashes, such as Perl's autovivification behavior 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 } } }


Got any Ruby Language Question?