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])- Expected output: ["apple"] ["tea"] false
- 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