0
0
Rubyprogramming~20 mins

Hash as named parameters pattern in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Hash as Named Parameters Pattern in Ruby
📖 Scenario: You are building a simple greeting system where users can provide their name and optional details like age and city. You want to use a Ruby method that accepts these details as named parameters using a hash.
🎯 Goal: Create a Ruby method that uses a hash as named parameters to greet a user with their name and optionally include their age and city in the greeting.
📋 What You'll Learn
Create a method called greet_user that accepts a single hash parameter named details.
The details hash must have a required key :name.
Optionally, the details hash can have keys :age and :city.
Inside the method, build a greeting string that always includes the :name.
If :age is provided, include it in the greeting.
If :city is provided, include it in the greeting.
Call the method with different hashes to test the greetings.
💡 Why This Matters
🌍 Real World
Using hashes as named parameters is common in Ruby gems and libraries to allow flexible method calls with optional settings.
💼 Career
Understanding this pattern helps you read and write Ruby code that is clean, flexible, and easy to maintain, which is valuable in Ruby development jobs.
Progress0 / 4 steps
1
Create the greet_user method with a details hash parameter
Write a method called greet_user that takes one parameter named details. Inside the method, create a variable greeting and set it to the string "Hello, " plus the value of details[:name].
Ruby
Need a hint?

Use details[:name] to access the name from the hash.

2
Add optional age and city to the greeting inside greet_user
Inside the greet_user method, add code to check if details[:age] exists. If it does, append ", age " plus the age to the greeting string. Then check if details[:city] exists. If it does, append ", from " plus the city to the greeting string.
Ruby
Need a hint?

Use if details[:age] and if details[:city] to check for optional keys.

3
Return the greeting string from the method
Modify the greet_user method to return the greeting string at the end.
Ruby
Need a hint?

Use return greeting to send the greeting string back to the caller.

4
Call greet_user with different hashes and print the results
Call greet_user with the hash {name: "Alice"} and print the result. Then call it with {name: "Bob", age: 30} and print the result. Finally, call it with {name: "Carol", city: "Paris"} and print the result.
Ruby
Need a hint?

Use puts greet_user({name: "Alice"}) to print the greeting.