liveBook · Manning

Hash.new

As explained in The Well-Grounded Rubyist, Fourth Edition

The Ruby Hash class method that creates a hash, optionally assigning a default value for nonexistent keys.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains empty construction, shared defaults, fresh block values, and automatic insertion, stopping short of broader hash mutation.
Examples
Demonstrates nil, numeric, shared-string, fresh-string, and auto-inserting defaults through IRB-sized hash lookups.
What it assumes
Assumes basic hash key/value lookup while establishing default-value behavior from simple examples.
What you can do after
Configure hashes with constant, freshly generated, or automatically inserted defaults.
How it connects
Connects hash construction with default values, blocks, key lookup, and key insertion.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.