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

Default Values

A default value gives a hash a backup answer for keys it does not have, like a helper who says zero if a name is not on the list. It avoids getting nothing back.

In this page:

  1. Default Values
Syntax
ruby
hash = Hash.new(default_value)
hash[missing_key]    # returns default_value

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using Hash.new([]) for an array default, where all keys share the same array; use Hash.new { |h, k| h[k] = [] }.
  2. Expecting a missing key to be added by a plain lookup, when Hash.new(0) returns the default without storing it.
  3. Forgetting += 1 needs a default, so counts[word] += 1 raises NoMethodError on the default nil.
Chapter Summary
  • Hashes store key-value pairs, and you access values by key.
  • each, map, select, reject, and merge process hashes.
  • Symbol keys and default values make hashes convenient.
🔒

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.