This page has content which requires Javascript to be displayed correctly, such as LaTeX formulae or code snippets. Your browser doesn't seem to support Javascript. Sorry if this causes any problems.

Getting a Method to Accept an Arbitrary Number of Arguments in Ruby

In LISP-like languages such as Scheme, you can do arithmetic with code like this:

  (+ 5 5)           ; => 10
  (- 3 2)           ; => 1

The + operator there behaves like a function. The striking thing is that it can accept any number of arguments. So you can also do stuff like this:

  (+ 1 2 3 4 5)     ; => 15

You can also do that in Ruby, using the splat(*) operator. The splat operator can do a lot of fancy stuff, but I'm not going to cover all of that here.

This is how you would use the splat operator in a method definition to achieve that.
  def func(param1, *rest)
    # Code goes here
  end
Due to the way we defined that method, it needs to have at least one argument passed to it when we call it. We can, however, pass it more arguments if we wish to.
  func('test')          # param1 = 'test', rest = []
  func('test', 1, 2, 3) # param1 = 'test', rest = [1, 2, 3]
We can implement a LISP-style add function like this:
  def add(*args)
    args.inject { |m, n| m += n } || 0
  end

  # Let's try out the add method
  add               # => 0
  add 5, 5          # => 10
  add 5, 5, 5       # => 15