Challenge - 5 Problems
Ruby Default Parameters Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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")
Attempts:
2 left
💡 Hint
Check which parameters are given and which use default values.
✗ Incorrect
The method greet has two parameters with default values. When called with one argument, the first parameter is set to "Alice" and the second uses its default "Hello". So the output is "Hello, Alice!".
❓ Predict Output
intermediate2: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
Attempts:
2 left
💡 Hint
No arguments are passed, so all default values are used.
✗ Incorrect
Both parameters a and b use their default values 5 and 10. The method returns 5 * 10 = 50.
🔧 Debug
advanced2: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)
Attempts:
2 left
💡 Hint
In Ruby, parameters with default values must come after parameters without defaults.
✗ Incorrect
Ruby does not allow a parameter with a default value (y=2) to be followed by a parameter without a default (z). This causes a SyntaxError.
❓ Predict Output
advanced2: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")
Attempts:
2 left
💡 Hint
Check how Ruby handles keyword arguments versus positional arguments.
✗ Incorrect
The method expects positional arguments, but city: "Paris" is a keyword argument. Ruby raises an ArgumentError because the method does not accept keyword arguments.
🧠 Conceptual
expert2: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
Attempts:
2 left
💡 Hint
Consider required, optional, splat, and default parameters in Ruby.
✗ Incorrect
'a' is required. 'b' has a default value, making it optional. '*c' collects any number (including zero) of additional arguments. 'd' is a required positional parameter after the splat. Therefore, at least 2 arguments are required (one for 'a' and one for 'd'), with no maximum due to the splat '*c'.