0
0
Rubyprogramming~20 mins

Hash as named parameters pattern in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Hash Named Parameters Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
AHello, Alice! You are 30 years old.
BHello, ! You are years old.
CHello, {:name=>"Alice", :age=>30}! You are years old.
DSyntaxError
Attempts:
2 left
💡 Hint
Look at how the method accesses the hash keys inside the string.
🧠 Conceptual
intermediate
2: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")
AHello, Bob! You are 25 years old.
BHello, Guest! You are 25 years old.
CHello, Bob! You are .
DHello, ! You are 25 years old.
Attempts:
2 left
💡 Hint
Check how default values are assigned using || operator.
🔧 Debug
advanced
2: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")
AArgumentError: wrong number of arguments (given 1, expected 0)
BNoMethodError: undefined method `[]' for nil:NilClass
CNo error, outputs: Hello, Eve!
DSyntaxError
Attempts:
2 left
💡 Hint
Check the method parameter and how the hash is passed.
Predict Output
advanced
2: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)
AArgumentError: wrong number of arguments
BOrder: Book, Quantity: , Price:
COrder: , Quantity: 3, Price: 15
DOrder: Book, Quantity: 3, Price: 15
Attempts:
2 left
💡 Hint
Look at how the method uses a positional parameter and an optional hash.
🧠 Conceptual
expert
2: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
A2
B3
C4
D1
Attempts:
2 left
💡 Hint
Merging hashes combines keys, with later keys overwriting earlier ones.