Hacking Ruby's default arguments 2
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.
Trackbacks
Use the following link to trackback from your own site:
http://www.mobalean.com/blog/trackbacks?article_id=11


[…] the value is really can be […]
Huh!?!?
impressive. in some ways, ruby is the new perl.