Hacking Ruby's default arguments 2

Posted by Paul McMahon Fri, 27 Feb 2009 22:34:00 GMT

The value of a default argument in Ruby is the result of an executed expression. Most of the time the value is set to some object:

def int(i=1) i; end
def str(s="") s; end

Under normal usage, the fact that the value can be arbitrary code isn't immediately apparent. However, the value really can be any code:

def foo(a = puts("bar")); end

Furthermore, previous arguments can be referenced in the default argument expression:

def bar(a,b=a) puts "a: #{a} b: #{b}"; end

I wondered how far I could take this, and came up with the following method:

def fib(n, t = n < 2 ? n : fib(n-1) + fib(n-2)) t; end

Although it makes little sense to define methods this way, it does highlight the power of Ruby's default arguments.