0
0
RubyHow-ToBeginner · 3 min read

How to Use Default Value in Hash Ruby: Simple Guide

In Ruby, you can set a default value for a hash using Hash.new(default_value) or by assigning a block with Hash.new { |hash, key| ... }. This default value is returned whenever you access a key that does not exist in the hash.
📐

Syntax

You can create a hash with a default value using two main ways:

  • Hash.new(default_value): Returns default_value for missing keys.
  • Hash.new { |hash, key| block }: Runs the block to compute the default value dynamically.

This helps avoid nil when accessing keys that are not set.

ruby
hash1 = Hash.new(0)
hash2 = Hash.new { |h, k| h[k] = [] }
💻

Example

This example shows how to use a default value of 0 for counting items and a default block to create empty arrays for new keys.

ruby
counts = Hash.new(0)
counts["apple"] += 1
counts["banana"] += 2

lists = Hash.new { |h, k| h[k] = [] }
lists["fruits"] << "apple"
lists["fruits"] << "banana"
lists["vegetables"] << "carrot"

puts counts
puts lists
Output
{"apple"=>1, "banana"=>2} {"fruits"=>["apple", "banana"], "vegetables"=>["carrot"]}
⚠️

Common Pitfalls

A common mistake is using Hash.new([]) which shares the same array for all missing keys, causing unexpected behavior.

Instead, use a block to create a new array for each key.

ruby
wrong = Hash.new([])
wrong[:a] << 1
wrong[:b] << 2
puts wrong[:a]  # Output: [1, 2] - unexpected shared array

right = Hash.new { |h, k| h[k] = [] }
right[:a] << 1
right[:b] << 2
puts right[:a]  # Output: [1]
puts right[:b]  # Output: [2]
Output
[1, 2] [1] [2]
📊

Quick Reference

MethodDescriptionExample
Hash.new(default_value)Returns the same default value for missing keysHash.new(0)
Hash.new { |hash, key| block }Runs block to set default value per keyHash.new { |h, k| h[k] = [] }
hash[key]Access value or default if key missinghash[:missing]
hash[key] = valueAssign value to keyhash[:key] = 10

Key Takeaways

Use Hash.new(default_value) to return a fixed default for missing keys.
Use Hash.new with a block to create dynamic or mutable defaults per key.
Avoid Hash.new([]) because it shares the same object for all keys.
Default values help prevent nil errors when accessing unknown keys.
Blocks allow you to initialize complex default values like arrays or hashes.