Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between "Hash.new(0)" and "{}"

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
like image 350
doub1ejack Avatar asked Feb 03 '16 13:02

doub1ejack


People also ask

What is Ruby hash New 0?

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.

What does hash new do in Ruby?

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.

What is returned if you pass a key that doesnt exist into a hash?

Typically when an element is passed into a hash with no matching key, the hash returns nil .

How do you define a hash in Ruby?

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.


1 Answers

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
like image 136
Rustam A. Gasanov Avatar answered Dec 01 '22 00:12

Rustam A. Gasanov