📖 Scenario: You are creating a simple program to greet people with personalized messages. You want to use keyword arguments in Ruby methods to make your greetings clear and flexible.
🎯 Goal: Build a Ruby method that uses keyword arguments to greet a person with their name and age. Then call the method with different keyword arguments and print the greetings.
📋 What You'll Learn
Create a method called greet that takes keyword arguments name and age
Inside the method, create a greeting string using the name and age arguments
Call the greet method with keyword arguments for name and age
Print the greeting returned by the greet method
💡 Why This Matters
🌍 Real World
Keyword arguments help make your Ruby methods clear and flexible, especially when many options or settings are needed. This is common in web apps, scripts, and libraries.
💼 Career
Understanding keyword arguments is important for writing clean, maintainable Ruby code in jobs like backend development, automation scripting, and working with Ruby frameworks like Rails.
Progress0 / 4 steps
1
Create the greet method with keyword arguments
Write a method called greet that takes two keyword arguments: name: and age:. Inside the method, create a variable message that stores the string "Hello, my name is #{name} and I am #{age} years old." Use string interpolation exactly as shown.
Ruby
Hint
Use def greet(name:, age:) to define the method with keyword arguments. Use double quotes and #{} for string interpolation.
2
Call the greet method with keyword arguments
Call the greet method with name: set to "Alice" and age: set to 30. Store the result in a variable called greeting.
Ruby
Hint
Call the method with greet(name: "Alice", age: 30) and assign it to greeting.
3
Return the greeting message from the method
Modify the greet method to return the message variable so that the greeting string is returned when the method is called.
Ruby
Hint
Add return message as the last line inside the method.
4
Print the greeting message
Write a puts statement to print the greeting variable to the console.
Ruby
Hint
Use puts greeting to print the greeting string.
Practice
(1/5)
1. What is the purpose of keyword arguments in Ruby methods?
easy
A. To convert all arguments into strings automatically
B. To force all arguments to be passed in order
C. To make arguments optional without default values
D. To allow passing arguments by name for clarity and flexibility
Solution
Step 1: Understand keyword arguments
Keyword arguments let you pass values to a method by naming them, not just by position.
Step 2: Identify the benefit
This makes code clearer and lets you skip or reorder arguments easily.
Final Answer:
To allow passing arguments by name for clarity and flexibility -> Option D
Quick Check:
Keyword arguments = named, clear, flexible [OK]
Hint: Keyword arguments are named for clarity and order freedom [OK]
Common Mistakes:
Thinking keyword arguments force order
Confusing keyword arguments with positional arguments
2. Which of the following is the correct syntax to define a method with keyword arguments in Ruby?
easy
A. def greet(name =>, age =>); puts "Hello #{name}, you are #{age}"; end
B. def greet(name, age); puts "Hello #{name}, you are #{age}"; end
C. def greet(name:, age:); puts "Hello #{name}, you are #{age}"; end
D. def greet(name =:, age =:); puts "Hello #{name}, you are #{age}"; end
Solution
Step 1: Review Ruby keyword argument syntax
Keyword arguments are defined with a colon after the argument name, like name:.
Step 2: Check each option
def greet(name:, age:); puts "Hello #{name}, you are #{age}"; end uses correct syntax with name: and age:. Others use invalid symbols or positional arguments.
Final Answer:
def greet(name:, age:); puts "Hello #{name}, you are #{age}"; end -> Option C
Quick Check:
Keyword args use colon after name [OK]
Hint: Keyword args end with colon in method definition [OK]
Common Mistakes:
Using => instead of : for keyword arguments
Defining keyword arguments without colons
Confusing positional and keyword argument syntax
3. What will be the output of the following Ruby code?
The method info has a required keyword argument name: and an optional keyword argument age: with default 30.
Step 2: Check method call
The call passes name: "Alice" but no age, so default 30 is used.
Final Answer:
Name: Alice, Age: 30 -> Option A
Quick Check:
Default keyword argument used when missing [OK]
Hint: Missing keyword uses default if provided [OK]
Common Mistakes:
Expecting error when optional keyword is missing
Confusing positional defaults with keyword defaults
Ignoring default values in keyword arguments
4. Identify the error in the following Ruby method call:
def order(item:, quantity:)
"Order: #{quantity} x #{item}"
end
puts order(quantity: 3, "apple")
medium
A. ArgumentError: missing keyword: item
B. SyntaxError due to positional argument after keyword argument
C. No error, prints 'Order: 3 x apple'
D. TypeError: wrong argument type String (expected Symbol)
Solution
Step 1: Examine method call arguments
The call uses quantity: 3 (keyword) then "apple" (positional).
Step 2: Understand Ruby argument rules
In Ruby, positional arguments cannot come after keyword arguments in a call; this causes a syntax error.
Final Answer:
SyntaxError due to positional argument after keyword argument -> Option B
Quick Check:
Positional args must come before keyword args [OK]
Hint: Positional args cannot follow keyword args in calls [OK]
Common Mistakes:
Passing positional argument after keyword argument
Assuming Ruby allows mixed order without error
Confusing missing keyword with syntax error
5. Given this method: <pre>def build_profile(name:, age:, city: "Unknown", **extras)
profile = {name: name, age: age, city: city}
profile.merge!(extras)
profile
end
What will be the result of build_profile(name: "Bob", age: 25, hobby: "guitar", pet: "dog")?
hard
A. {:name=>"Bob", :age=>25, :city=>"Unknown", :hobby=>"guitar", :pet=>"dog"}
B. {:name=>"Bob", :age=>25, :city=>"Unknown"}
C. ArgumentError: unknown keyword: hobby
D. {:name=>"Bob", :age=>25, :city=>"Unknown", :extras=>{:hobby=>"guitar", :pet=>"dog"}}
Solution
Step 1: Understand method parameters
The method requires name and age, has optional city with default, and collects extra keyword arguments into extras.
Step 2: Analyze method call
The call passes name, age, and extra keywords hobby and pet. These extras are merged into the profile hash.
Step 3: Determine final hash
The returned hash includes all keys: name, age, default city, plus hobby and pet from extras.
Final Answer:
{:name=>"Bob", :age=>25, :city=>"Unknown", :hobby=>"guitar", :pet=>"dog"} -> Option A
Quick Check:
Extras merged into hash with defaults [OK]
Hint: Use **extras to capture and merge extra keyword args [OK]
Common Mistakes:
Expecting error on unknown keywords with **extras
Forgetting to merge extras into profile
Assuming extras stored under :extras key
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.