Hash.new creates an empty Ruby hash. With no argument, looking up a nonexistent key returns nil; with an argument, that argument becomes the hash's default value. section 9.3.1 section 9.3.3
Choose the form that matches the behavior you need:
- Use Hash.new for an empty hash whose missing keys return nil. section 9.3.3
- Use Hash.new(0) or another argument when every missing key should return the same default object. section 9.3.3
- Use a block when each missing-key lookup should produce a fresh value. section 9.3.3
- Use a block that assigns through the hash when looking up a missing key should create that key. section 9.3.3
Shared defaults versus fresh defaults
h = Hash.new("No such key!") returns the same string object for every missing key, so modifying the result for one lookup affects later lookups. By contrast, Hash.new { "No such key!" } creates a new string on each lookup. section 9.3.3
Creating keys on first lookup
h = Hash.new { |hash, key| hash[key] = 0 } makes h["new key!"] return 0 and leaves h containing {"new key!"=>0}. A default lookup alone does not create a key. section 9.3.3
h = Hash.new {|hash,key| hash[key] = 0 }
Inspect the block form that initializes missing keys during lookup. section 9.3.3
