0
0
RubyHow-ToBeginner · 3 min read

How to Use Variable Arguments in Ruby: Simple Guide

In Ruby, you can use *args in a method definition to accept any number of arguments as an array. This lets your method handle variable arguments flexibly without specifying a fixed number.
📐

Syntax

Use *args in the method parameters to collect all extra arguments into an array named args. You can name args anything you like, but the asterisk * is required.

This allows the method to accept zero or more arguments.

ruby
def example_method(*args)
  puts "Number of arguments: #{args.length}"
  puts "Arguments: #{args.inspect}"
end
💻

Example

This example shows a method that sums any number of numbers passed to it using variable arguments.

ruby
def sum_all(*numbers)
  total = 0
  numbers.each { |num| total += num }
  total
end

puts sum_all(1, 2, 3)       # Output: 6
puts sum_all(10, 20, 30, 40) # Output: 100
puts sum_all()               # Output: 0
Output
6 100 0
⚠️

Common Pitfalls

One common mistake is forgetting the * before the parameter name, which causes Ruby to expect exactly one argument instead of multiple.

Another pitfall is mixing variable arguments with regular parameters incorrectly, which can lead to unexpected argument errors.

ruby
def wrong_method(args)
  puts args.inspect
end

# Calling with multiple arguments causes error:
# wrong_method(1, 2, 3) # ArgumentError

# Correct way:
def right_method(*args)
  puts args.inspect
end

right_method(1, 2, 3) # Outputs: [1, 2, 3]
Output
[1, 2, 3]
📊

Quick Reference

  • *args: collects extra arguments into an array.
  • You can combine fixed and variable arguments: def method(a, b, *args).
  • Use args as a normal array inside the method.

Key Takeaways

Use * before a parameter name to accept variable arguments as an array.
Variable arguments let methods handle any number of inputs flexibly.
Forget the * and Ruby expects exactly one argument, causing errors.
You can mix fixed and variable arguments in method definitions.
Inside the method, variable arguments behave like a normal array.