Here is a snippet of code
myHash = Hash.new {|h, k| h[k] = []}
myHash[5] << 1
Marshal.dump(myHash)
I use this often when I try to use it with arbitrary keys, and I did not want to explicitly write something like this
myHash = Hash.new
myHash[5] ||= []
myHash[5] << 1
Marshal.dump(myHash)
While this is only one line of difference in code, for me, using a block version looks a bit cleaner.
However, there are problems during the serialization process.
in `dump: can't dump hash with default proc (TypeError)
Is there a way to serialize this while continuing to use the block form constructor? Or should I stick to explicitly checking and initializing any values before trying to work with my hash?
I would say no, because there is no real way for a ruby to determine how the hash should automatically generate a value when there is no key without the original proc that was passed.
source