How to Allow Any Number of Arguments in Ruby Methods

August 29, 2012

When calling a ruby method (note: in this article, I’m writing with respect to Ruby version 1.9.x), you must supply the correct number of arguments, otherwise you will get an error. Consider the following:

def method1(x,y)
  puts "Hello, I require 2 arguments."
end

Calling method1(1) will give you an error like the following:

ArgumentError: wrong number of arguments (1 for 2)

If you want to allow zero or more arguments, try using the splat operator

The splat operator (also known as an asterisk "*") can be used as follows:

def method2(*args)
  puts "Hello, zero or more arguments in #{args} is all I need"
end

Using *args means that when you call method2, you can supply zero or more arguments.

You can also have a combination of required and optional arguments:

def drive_car(driver_name, *cars)
  cars.each { |c| puts "#{driver_name} drives #{c}"}
end

So calling drive_car("Bob", "mustang", "fiesta", "ranger") outputs:

Bob drives mustang
Bob drives fiesta
Bob drives ranger
=> ["mustang", "fiesta", "ranger"]

You can also use the splat operator when calling a method

So after running the following code,

mycars = ["mustang", "fiesta", "ranger"]
drive_car("Sally", *mycars)

ruby will give the output:

Sally drives mustang
Sally drives fiesta
Sally drives ranger
=> ["mustang", "fiesta", "ranger"]

In an upcoming article, I’ll talk about the order of method arguments with the splat operator.


Profile picture

Written by Bruce Park who lives and works in the USA building useful things. He is sometimes around on Twitter.