Challenge - 5 Problems
Ruby Variable-length Arguments Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of method using *args with sum
What is the output of this Ruby code?
def sum_all(*numbers)
numbers.reduce(0) { |sum, n| sum + n }
end
puts sum_all(1, 2, 3, 4)Ruby
def sum_all(*numbers) numbers.reduce(0) { |sum, n| sum + n } end puts sum_all(1, 2, 3, 4)
Attempts:
2 left
💡 Hint
Remember *args collects all arguments into an array.
✗ Incorrect
The method sum_all collects all arguments into an array called numbers. Then it sums them using reduce starting from 0. So 1+2+3+4 = 10.
❓ Predict Output
intermediate2:00remaining
Output when mixing fixed and variable arguments
What will this Ruby code print?
def greet(greeting, *names)
names.map { |name| "#{greeting}, #{name}!" }
end
puts greet("Hello", "Alice", "Bob").join(", ")Ruby
def greet(greeting, *names) names.map { |name| "#{greeting}, #{name}!" } end puts greet("Hello", "Alice", "Bob").join(", ")
Attempts:
2 left
💡 Hint
The first argument is fixed, the rest go into *names.
✗ Incorrect
The method takes a fixed greeting and any number of names. It returns an array of greetings for each name. Joining with ', ' prints them separated by commas.
🔧 Debug
advanced2:00remaining
Identify the error in this method using *args
What error does this Ruby code raise?
def multiply(*nums) nums * nums end puts multiply(3, 4)
Ruby
def multiply(*nums) nums * nums end puts multiply(3, 4)
Attempts:
2 left
💡 Hint
What happens when you multiply an array by another array in Ruby?
✗ Incorrect
In Ruby, multiplying an array by an integer repeats the array elements. But here nums is an array and nums * nums tries to multiply array by array, causing a TypeError.
📝 Syntax
advanced2:00remaining
Which method definition correctly uses *args?
Which of these Ruby method definitions correctly accepts any number of arguments?
Attempts:
2 left
💡 Hint
Look for correct syntax and valid operations on args.
✗ Incorrect
Option B correctly defines *args and sums the array. B has invalid syntax. C tries to add 1 to an array causing error. D tries to add 1 to an enumerator causing error.
🚀 Application
expert3:00remaining
What is the output of this recursive method using *args?
Consider this Ruby code:
What is the output?
def recursive_sum(*nums) return 0 if nums.empty? nums[0] + recursive_sum(*nums[1..]) end puts recursive_sum(5, 10, 15)
What is the output?
Ruby
def recursive_sum(*nums) return 0 if nums.empty? nums[0] + recursive_sum(*nums[1..]) end puts recursive_sum(5, 10, 15)
Attempts:
2 left
💡 Hint
The method sums the first number plus the sum of the rest recursively.
✗ Incorrect
The method recursively sums all numbers by adding the first element to the sum of the rest until no numbers remain. So 5 + 10 + 15 = 30.