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
In short, Hash. new(some_value) sets a default value of some_value for every key that does not exist in the hash, Hash. new {|hash, key| block } creates a new default object for every key that does not exist in the hash, and Hash. new() or {} sets nil for every key.
2. new : This method returns a empty hash. If a hash is subsequently accessed by the key that does not match to the hash entry, the value returned by this method depends upon the style of new used to create a hash.
Typically when an element is passed into a hash with no matching key, the hash returns nil .
In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.
Hash.new(0)
sets default value for any key to 0
, while {}
sets nil
h1 = Hash.new(0)
h1.default # => 0
h1[:a] += 1 # => 1
h2 = {}
h2.default # => nil
h2[:a] += 1 # => NoMethodError: undefined method `+' for nil:NilClass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With