rubydefaultnew-operatorruby-hash

Working with Hashes that have a default value


Am learning to code with ruby. I am learning about hashes and i dont understand this code: count = Hash.new(0). It says that the 0 is a default value, but when i run it on irb it gives me an empty hash {}. If 0 is a default value why can't i see something like count ={0=>0}. Or is the zero an accumulator but doesn't go to the keys or values? Thanks


Solution

  • 0 will be the fallback if you try to access a key in the hash that doesn't exist

    For example:

    count = Hash.new -> count['key'] => nil

    vs

    count = Hash.new(0) -> count['key'] => 0