0
0
Rubyprogramming~20 mins

Parameters with default values in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Default Parameters Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of method with default parameters
What is the output of this Ruby code?
Ruby
def greet(name = "Guest", greeting = "Hello")
  "#{greeting}, #{name}!"
end

puts greet("Alice")
AHello, Guest!
BAlice, Hello!
CHello, Alice!
DError: wrong number of arguments
Attempts:
2 left
💡 Hint
Check which parameters are given and which use default values.
Predict Output
intermediate
2:00remaining
Method call with all default parameters
What will this Ruby code print?
Ruby
def calculate(a = 5, b = 10)
  a * b
end

puts calculate
A50
B15
CError: wrong number of arguments
D0
Attempts:
2 left
💡 Hint
No arguments are passed, so all default values are used.
🔧 Debug
advanced
2:00remaining
Identify the error in method with default parameters
What error does this Ruby code raise when run?
Ruby
def add(x, y = 2, z)
  x + y + z
end

puts add(1, 3, 4)
ANo error, outputs 8
BSyntaxError: default argument followed by non-default argument
CTypeError: undefined method '+' for nil:NilClass
DArgumentError: wrong number of arguments (given 3, expected 2)
Attempts:
2 left
💡 Hint
In Ruby, parameters with default values must come after parameters without defaults.
Predict Output
advanced
2:00remaining
Output with mixed default and explicit parameters
What is the output of this Ruby code?
Ruby
def info(name = "Unknown", age = 0, city = "Nowhere")
  "#{name} is #{age} years old and lives in #{city}."
end

puts info("Bob", city: "Paris")
ABob is city: Paris years old and lives in Nowhere.
BBob is 0 years old and lives in Nowhere.
CBob is 0 years old and lives in Paris.
DError: wrong number of arguments
Attempts:
2 left
💡 Hint
Check how Ruby handles keyword arguments versus positional arguments.
🧠 Conceptual
expert
2:00remaining
Number of parameters in method with defaults and splat
Given this Ruby method, how many arguments can it accept without error?
Ruby
def example(a, b = 2, *c, d)
  [a, b, c, d]
end
AAt least 2 arguments, no maximum limit
BExactly 4 arguments only
CAt least 3 arguments, no maximum limit
DAt least 1 argument, no maximum limit
Attempts:
2 left
💡 Hint
Consider required, optional, splat, and default parameters in Ruby.