0
0
Rubyprogramming~15 mins

Default values for missing keys in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
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' => 0
Set the default value of borrowed_books to 0
Access 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
1
Create the initial hash
Create a hash called borrowed_books with these exact entries: 'Alice' => 3, 'Bob' => 5, 'Charlie' => 0
Ruby
Need a hint?

Use curly braces {} to create a hash and separate keys and values with =>.

2
Set the default value for missing keys
Set the default value of the hash borrowed_books to 0 so that missing keys return 0 instead of nil
Ruby
Need a hint?

Use hash.default = value to set a default value for missing keys.

3
Access a missing key
Access the borrowed book count for the member 'Diana' from the hash borrowed_books and store it in a variable called diana_books
Ruby
Need a hint?

Use hash[key] to get the value for a key.

4
Print the result
Print the value of the variable diana_books to show the borrowed book count for 'Diana'
Ruby
Need a hint?

Use puts variable_name to print the value.