0
0
Rubyprogramming~5 mins

Variable-length arguments (*args) in Ruby

Choose your learning style9 modes available
Introduction

Sometimes you want a method to accept any number of inputs. Variable-length arguments let you do that easily.

When you want a method to add any number of numbers together.
When you want to print a list of items without knowing how many there are.
When you want to pass a flexible number of options to a method.
When you want to collect multiple values into one parameter inside a method.
Syntax
Ruby
def method_name(*args)
  # use args as an array inside
end

The * before args means 'collect all extra arguments into an array called args.'

You can name args anything you want, but *args is the common style.

Examples
This method greets any number of people by name.
Ruby
def greet(*names)
  names.each { |name| puts "Hello, #{name}!" }
end

greet('Alice', 'Bob', 'Carol')
This method adds all given numbers and returns the total.
Ruby
def sum_all(*numbers)
  numbers.sum
end

puts sum_all(1, 2, 3, 4)
This method shows how to use *args with other regular arguments.
Ruby
def show_args(first, *rest)
  puts "First: #{first}"
  puts "Rest: #{rest.inspect}"
end

show_args('a', 'b', 'c', 'd')
Sample Program

This program lists all items passed to the method, showing how many and what they are.

Ruby
def list_items(*items)
  puts "You gave me #{items.length} items:"
  items.each_with_index do |item, index|
    puts "#{index + 1}. #{item}"
  end
end

list_items('apple', 'banana', 'cherry')
OutputSuccess
Important Notes

Inside the method, *args is just a normal array you can loop over or check length.

You can combine *args with regular arguments, but *args must come last.

Summary

*args lets a method accept any number of arguments as an array.

Use *args when you don't know how many inputs you will get.

Inside the method, treat *args like a normal array.