Default Values for Ruby Hashes
Setting a default for ruby hashes which returns a new object
Setting a default for ruby hashes which returns a new object.
I can't tell you how many times I've looked this up, so I'm scribbling it down here. Here we want a hash value which doesn't yet exist to be initialised to an empty array.
langs = Hash.new { |hash, key| hash[key] = [] }
Now we can do:
langs[:billy] << 'ruby' << 'elixir'
Without having to set langs[:billy]
to an empty array first.
Member discussion