Default values for missing keys
📖 Scenario: Imagine you run a small library. You keep track of how many books each member has borrowed using a Ruby hash. Sometimes, a member might not have borrowed any books yet, so their name won't be in the hash. You want to make sure that when you check the number of books borrowed, you get 0 instead of nil for those members.
🎯 Goal: You will create a Ruby hash with some members and their borrowed book counts. Then, you will set a default value so that if you ask for a member not in the hash, it returns 0 instead of nil.
📋 What You'll Learn
Create a hash called
borrowed_books with exact entries: 'Alice' => 3, 'Bob' => 5, 'Charlie' => 0Set the default value of
borrowed_books to 0Access the borrowed book count for
'Diana' (a member not in the hash)Print the borrowed book count for
'Diana'💡 Why This Matters
🌍 Real World
Setting default values in hashes helps avoid errors when looking up data that might not exist yet, like tracking user activity or inventory counts.
💼 Career
Many programming jobs require handling data collections safely. Knowing how to set default values in hashes is a common and useful skill in Ruby development.
Progress0 / 4 steps