Default Values
In this page:
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
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: