← Back to Ruby Course | Chapter 5: Hashes | Lesson 7 of 7

Default Values

In this page:

  1. Default Values

Default Values

Hash.new(default_value) creates a hash that returns a specified default instead of nil when you access a missing key, without actually adding that key to the hash. Hash.new { |hash, key| ... } takes a block form that can compute a default dynamically, and optionally insert it into the hash. This is a common technique for building counters or grouping data without manually checking nil every time.

Note: Hash.new(0) is the classic idiom for a counting hash -- counts[word] += 1 works immediately without checking if the key exists first.

Example: Default Values

markup
counts = Hash.new(0)

words = ["apple", "banana", "apple", "cherry", "apple"]
words.each { |word| counts[word] += 1 }

puts counts.inspect
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.