Bird
Raised Fist0
Rubyprogramming~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main advantage of using a hash as named parameters in a Ruby method?
easy
A. It improves the method's execution speed significantly.
B. It forces the method to accept only one argument.
C. It makes the method call clearer by naming each argument explicitly.
D. It prevents any default values from being used.

Solution

  1. Step 1: Understand named parameters purpose

    Named parameters improve code readability by explicitly naming each argument passed to a method.
  2. Step 2: Compare with other options

    Options B, C, and D are incorrect because using a hash does not limit argument count to one, does not speed up execution notably, and does not prevent default values.
  3. Final Answer:

    It makes the method call clearer by naming each argument explicitly. -> Option C
  4. Quick Check:

    Named parameters = clearer calls [OK]
Hint: Named parameters improve clarity by naming each argument [OK]
Common Mistakes:
  • Thinking it limits arguments to one
  • Assuming it speeds up code
  • Believing it disables default values
2. Which of the following is the correct syntax to define a method using a hash for named parameters in Ruby?
easy
A. def greet(name: options = {})
B. def greet(name, options = {})
C. def greet(options: {})
D. def greet(options = [])

Solution

  1. Step 1: Identify correct method parameter syntax

    In Ruby, to accept named parameters as a hash, you define the method with a parameter defaulting to an empty hash, like options = {}.
  2. Step 2: Check each option

    def greet(name, options = {}) uses options = {} correctly. def greet(name: options = {}) uses invalid syntax. def greet(options: {}) tries to use keyword arguments incorrectly. def greet(options = []) uses an array instead of a hash.
  3. Final Answer:

    def greet(name, options = {}) -> Option B
  4. Quick Check:

    Hash parameter = options = {} [OK]
Hint: Use options = {} to accept named parameters as a hash [OK]
Common Mistakes:
  • Using square brackets [] instead of curly braces {}
  • Confusing keyword arguments with hash parameters
  • Incorrect syntax like name: options = {}
3. What will be the output of the following Ruby code?
def info(options = {})
  "Name: #{options[:name]}, Age: #{options[:age]}"
end

puts info(name: "Alice", age: 30)
medium
A. Name: , Age:
B. Error: wrong number of arguments
C. Name: {:name=>"Alice"}, Age: {:age=>30}
D. Name: Alice, Age: 30

Solution

  1. Step 1: Understand method call with hash named parameters

    The method info accepts a hash options. The call info(name: "Alice", age: 30) passes a hash with keys :name and :age.
  2. Step 2: Evaluate string interpolation

    The method returns a string with values from the hash accessed by options[:name] and options[:age], which are "Alice" and 30 respectively.
  3. Final Answer:

    Name: Alice, Age: 30 -> Option D
  4. Quick Check:

    options[:name], options[:age] = Alice, 30 [OK]
Hint: Access hash keys with options[:key] inside method [OK]
Common Mistakes:
  • Expecting error due to multiple arguments
  • Confusing hash keys with string keys
  • Not using symbol keys for access
4. Identify the error in the following Ruby method using hash named parameters:
def display(options = {})
  puts "Title: #{options[:title]}"
  puts "Author: #{options[:author]}"
end

display(title: "Ruby Guide")
medium
A. It prints Title but prints nothing for Author without error.
B. It raises an error because :author key is missing in options.
C. Syntax error due to missing parentheses in method call.
D. No error; it prints Title and Author correctly.

Solution

  1. Step 1: Analyze method call and parameters

    The method display is called with a hash containing only :title. The :author key is missing.
  2. Step 2: Understand Ruby hash access behavior

    Accessing a missing key like options[:author] returns nil, which prints as empty string without error.
  3. Final Answer:

    It prints Title but prints nothing for Author without error. -> Option A
  4. Quick Check:

    Missing key returns nil, no error [OK]
Hint: Missing hash keys return nil, print empty string [OK]
Common Mistakes:
  • Expecting a runtime error for missing keys
  • Thinking missing keys print 'nil' string
  • Assuming syntax error without parentheses
5. Given the method below, how can you modify it to provide a default value of 18 for the :age key if it is not passed?
def person_info(options = {})
  "Name: #{options[:name]}, Age: #{options[:age]}"
end

puts person_info(name: "Bob")
hard
A. Use options[:age] || 18 inside the string interpolation.
B. Set default value in method definition like def person_info(options = {age: 18}).
C. Raise an error if :age is missing to force passing it.
D. Use options.fetch(:age) without default to get 18.

Solution

  1. Step 1: Understand default value requirement

    We want to show 18 if :age is missing in options.
  2. Step 2: Use Ruby's || operator for default

    Using options[:age] || 18 returns options[:age] if present, otherwise 18.
  3. Step 3: Check other options

    Set default value in method definition like def person_info(options = {age: 18}). sets default hash but can be overridden incorrectly. Raise an error if :age is missing to force passing it. raises error, not default. Use options.fetch(:age) without default to get 18. fetch without default raises error if missing.
  4. Final Answer:

    Use options[:age] || 18 inside the string interpolation. -> Option A
  5. Quick Check:

    Default with || operator = 18 [OK]
Hint: Use options[:key] || default_value for defaults [OK]
Common Mistakes:
  • Setting default hash in parameter incorrectly
  • Using fetch without default causing error
  • Raising error instead of providing default
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard