0
0
Rubyprogramming~20 mins

Variable-length arguments (*args) in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Variable-length Arguments Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
AError: wrong number of arguments
B1234
C10
Dnil
Attempts:
2 left
💡 Hint
Remember *args collects all arguments into an array.
Predict Output
intermediate
2: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(", ")
AHello, Alice!, Hello, Bob!
BHello, Alice, Bob!
CError: wrong number of arguments
DHello, !, Hello, !
Attempts:
2 left
💡 Hint
The first argument is fixed, the rest go into *names.
🔧 Debug
advanced
2: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)
ATypeError: Array can't be coerced into Integer
BNoMethodError: undefined method '*' for Array
CSyntaxError: unexpected '*'
DOutput: [6, 8]
Attempts:
2 left
💡 Hint
What happens when you multiply an array by another array in Ruby?
📝 Syntax
advanced
2:00remaining
Which method definition correctly uses *args?
Which of these Ruby method definitions correctly accepts any number of arguments?
Adef example(*args); args.each + 1; end
Bdef example(*args); args.sum; end
Cdef example(*args); args + 1; end
Ddef example(args*); args.sum; end
Attempts:
2 left
💡 Hint
Look for correct syntax and valid operations on args.
🚀 Application
expert
3:00remaining
What is the output of this recursive method using *args?
Consider this Ruby code:
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)
Anil
BError: stack level too deep
C15
D30
Attempts:
2 left
💡 Hint
The method sums the first number plus the sum of the rest recursively.