Challenge - 5 Problems
Hash Named Parameters Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of method using hash as named parameters
What is the output of this Ruby code using a hash as named parameters?
Ruby
def greet(options = {}) "Hello, #{options[:name]}! You are #{options[:age]} years old." end puts greet(name: "Alice", age: 30)
Attempts:
2 left
💡 Hint
Look at how the method accesses the hash keys inside the string.
✗ Incorrect
The method greet takes a hash with keys :name and :age and inserts their values into the string. The output prints the greeting with the provided values.
🧠 Conceptual
intermediate2:00remaining
Understanding default values in hash named parameters
Given the method below, what will be the output of
greet(name: "Bob")?Ruby
def greet(options = {}) name = options[:name] || "Guest" age = options[:age] || 25 "Hello, #{name}! You are #{age} years old." end puts greet(name: "Bob")
Attempts:
2 left
💡 Hint
Check how default values are assigned using || operator.
✗ Incorrect
Since :age is not provided, the default 25 is used. The name is given as "Bob", so it is used directly.
🔧 Debug
advanced2:00remaining
Identify the error in hash named parameters usage
What error does this Ruby code raise when calling
greet(name: "Eve")?Ruby
def greet(options) "Hello, #{options[:name]}!" end greet(name: "Eve")
Attempts:
2 left
💡 Hint
Check the method parameter and how the hash is passed.
✗ Incorrect
The method expects one argument, a hash, and accesses the :name key correctly. The call passes a hash, so it works fine and outputs the greeting.
❓ Predict Output
advanced2:00remaining
Output when mixing positional and hash named parameters
What is the output of this Ruby code?
Ruby
def order(item, options = {}) "Order: #{item}, Quantity: #{options[:quantity] || 1}, Price: #{options[:price] || 0}" end puts order("Book", quantity: 3, price: 15)
Attempts:
2 left
💡 Hint
Look at how the method uses a positional parameter and an optional hash.
✗ Incorrect
The method receives "Book" as the first argument and a hash with quantity and price. It uses default values if keys are missing, but here both keys are present.
🧠 Conceptual
expert2:00remaining
How many keys in the hash after merging named parameters?
Consider this Ruby code. How many keys does the
params hash have after merging?Ruby
def process(params = {}) defaults = {color: "red", size: "medium"} params = defaults.merge(params) params end result = process(size: "large", weight: "heavy") puts result.keys.size
Attempts:
2 left
💡 Hint
Merging hashes combines keys, with later keys overwriting earlier ones.
✗ Incorrect
The defaults hash has keys :color and :size. The params hash has :size and :weight. After merging, keys are :color, :size, and :weight, total 3 keys.