1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Soaking Method Arguments

By

1 of 2

Soaking Method Arguments

There are a lot of methods that are able to take any number of arguments. For example, the ubiquitous puts will accept any number of arguments and output each separated by newlines. How this is done is not obvious at first.

An unknown (and unlimited) number of arguments is achieved by using the splat/soak operator on one of your method arguments. This argument will become a list, and contain any arguments passed to the method (other than ones already taken by other arguments). So in the following example, when the method is called with the arguments :a, :b, and :c, the arugment args will be an array equal to [:a, :b, :c].


def meth(*args)
 # Do something
end

meth(:a, :b, :c)

As mentioned before, there can also be a number of other arguments in the argument list. How exactly this acts is up to your Ruby version, however. Prior to Ruby 1.9.x, your soak argument could only be the last in the argument list.


def meth(a, b, *args)
 # First two arguments are a and b
 # The rest go to args
end

meth 1, 2, :a, :b, :c
# The args argument will be [:a, :b, :c]

In Ruby 1.9.x, your soak argument can be anywhere in the argument list. Ruby will work out what goes where when you call the method.


def meth(a, b, *args, c, d)
 # The args variable will soak up all arguments
 # except the first and last two
end

meth 1, 2, :a, :b, :c, 3, 4
# args will be [:a, :b, :c]

But note that you cannot have more than one soak argument in an argument list. Ruby can't infer the intended usage of the arguments, it wouldn't know how to distribute them.

The soak argument can soak zero arguments as well, in which case it will be an empty list. What happens here is clear in the 1.8.x behavior, where the soak operator can only be the last in the argument list. Any arguments passed will go to the named arguments and the soak argument will be an empty list.


def meth(a, b, *args)
end

meth :a, :b
# args will be an empty list []

However, what happens when you have a 1.9.x-style soak argument in the middle of an argument list is not immediately clear. Remember that Ruby must fill all of the named non-soak operators when the method is called, or else there will be an ArgumentError raised. So, if you have a soak operator in the middle of the argument list, the named arguments will be filled first from the beginning and end of the passed arguments, and if there are any left over in the middle, they'll be added to the soak argument list.


def meth(a, b, *args, c)
end

meth :a, :b, :c
# args will be an empty list []

meth :a, :b, :c, :d
# args will be [:c]
  1. About.com
  2. Technology
  3. Ruby

©2014 About.com. All rights reserved.