I was getting an unexpected (to me) behavior in my code so I tried to isolate the problem in the REPL. However these constructors both appear to have the same result (an empty hash):
irb> a = {}
# => {}
irb> b = Hash.new(0)
# => {}
When I pass {}
into a reduce function I get a NoMethodError, though. What is the difference between these two constructors?
irb> arr = "count the occurance of each of the words".scan(/\w+/)
# => ["count", "the", "occurance", "of", "each", "of", "the", "words"]
irb> x = arr.reduce(Hash.new(0)) { |hsh, word| hsh[word] += 1; hsh }
# => {"count"=>1, "the"=>2, "occurance"=>1, "of"=>2, "each"=>1, "words"=>1}
irb> x = arr.reduce({}) { |hsh, word| hsh[word] += 1; hsh }
# NoMethodError: undefined method `+' for nil:NilClass