Codectionary / Developer documentation / Ruby

Hash Default Blocks

A Hash default block creates a value on demand for an absent key. Assigning inside the block stores that new value independently for each key. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

Syntax

Hash.new { |hash, key| hash[key] = [] }

Examples

Hash Default Blocks

Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

groups = Hash.new { |hash, key| hash[key] = [] }
groups[:fruit] << "apple"
groups[:drink] << "tea"
p groups[:fruit]
p groups[:drink]
puts groups[:fruit].equal?(groups[:drink])
  1. Expected output: ["apple"] ["tea"] false
  2. The block creates two separate arrays and writes each into the hash. Hash.new([]) would instead share one unstored default array.

Best practices

  • Use a default block for mutable defaults rather than a shared array or hash.
  • Remember that a missing-key lookup can mutate the hash when the block assigns.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

Specifications & further reading