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:
Syntax
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
counts = Hash.new(0)
words = ["apple", "banana", "apple", "cherry", "apple"]
words.each { |word| counts[word] += 1 }
puts counts.inspect
Login to try C/C++/Java/PHP code in the editor
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
- Using
Hash.new([])for an array default, where all keys share the same array; useHash.new { |h, k| h[k] = [] }. - Expecting a missing key to be added by a plain lookup, when
Hash.new(0)returns the default without storing it. - Forgetting
+= 1needs a default, socounts[word] += 1raisesNoMethodErroron the defaultnil.
Chapter Summary
- Hashes store key-value pairs, and you access values by key.
each,map,select,reject, andmergeprocess 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: