Sponging: What You Can and Can’t Do In Argument Lists

September 29, 2012

What is a sponge argument?

A sponge argument is a parameter that “soaks up” any unassigned argument values in a ruby method call.

How Ruby Handles Assigning Values to Method Arguments

Ruby tries to assign values to as many variables as possible and a sponge argument gets the lowest priority. This means that the sponge argument will be empty if all the required arguments “soak up” the argument values. Let’s look at some examples.

Case 1: Sponge with default arguments

Here’s an example function “funky”
def funky(a=3,*b,c)
  puts "funky Arguments:"
  p a,b,c
end
Here’s the output of funky when called with one argument…
1.9.3p194> funky(2)
funky Arguments:
3
[]
2
=> [3, [], 2]

You’ll notice that because the sponge gets the lowest priority, the required argument “c” gets assigned the value of 2 while a gets its default value of 3.

Case 2: Sponge with not enough arguments

Here’s an example function “func_it”
def func_it(a,*b,c,d,e)
  puts "Arguments:"
  p a,b,c,d,e
end
Here’s the output of func_it when called with four arguments…
1.9.3p194> func_it(1,2,3,4)
Arguments:
1
[]
2
3
4
=> [1, [], 2, 3, 4]

Again, notice that because the sponge argument gets the lowest priority, that arguments a, c, d, and e get the argument values. Also note that if you had tried to call func_it with less than 4 arguments, you would have received an error because there are 4 required arguments.

Case 3: Sponge with too many arguments

Here’s the output of func_it when called with six arguments…

1.9.3p194> func_it(1,2,3,4,5,6)
Arguments:
1
[2, 3]
4
5
6
=> [1, [2, 3], 4, 5, 6]

In this case, you’ll notice the sponge soaks up two of the six arguments.

What You Can’t Do: Default Arguments to the Right of the Sponge

I could not have defined “funky” this way:

def funky(a, *b, c=3)
#some code
end

This is because once I assigned a value to “a”, *b would have soaked up all the remaining argument values, leaving nothing for “c”. This would result in an “ArgumentError: wrong number of arguments”.


Profile picture

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