0
0
Rubyprogramming~5 mins

Default values for missing keys in Ruby

Choose your learning style9 modes available
Introduction
Sometimes you want to get a value from a dictionary (hash) but the key might not be there. Default values help by giving you a safe answer instead of an error.
When you want to count things and start from zero if the key is new.
When you want to return a message or value if a key is missing.
When you want to avoid checking if a key exists every time you access it.
Syntax
Ruby
hash = Hash.new(default_value)
The default_value is returned whenever you access a key that does not exist in the hash.
You can also set a block to calculate default values dynamically.
Examples
Creates a hash with default 0. Increments :a, prints 1. :b is missing, so prints 0.
Ruby
h = Hash.new(0)
h[:a] += 1
puts h[:a]
puts h[:b]
Creates a hash with default empty array. Adds 1 to :a array. :b is missing, so returns empty array.
Ruby
h = Hash.new { |hash, key| hash[key] = [] }
h[:a] << 1
puts h[:a].inspect
puts h[:b].inspect
Sample Program
This program counts how many times each word appears in the list. It uses a hash with default 0 so it can add counts without errors.
Ruby
counts = Hash.new(0)
words = ["apple", "banana", "apple", "orange", "banana", "apple"]

words.each do |word|
  counts[word] += 1
end

counts.each do |word, count|
  puts "#{word}: #{count}"
end
OutputSuccess
Important Notes
If you use a mutable object like an array or hash as default, be careful because the same object is shared for all missing keys unless you use a block.
Using a block to set default values lets you create a new object for each missing key.
Summary
Default values let you avoid errors when accessing missing keys in a hash.
You can set a fixed default value or use a block to create dynamic defaults.
This makes your code simpler and safer when working with hashes.