December 14th, 2006
Another neat trick
Another sweet thing, that I’ve actually wondered idly about from time to time, is how you could get “provided?”-style parameters in Ruby. If you have used a language with this functionality, like Common Lisp for example, you know that this can be highly useful.
And just the other day, while reading Hal Fultons excellent (but poorly proof read) The Ruby Way (2nd ed) I found the way. Ergo, it looks like this:
def foo(bar, baz = (baz_provided=true; 42))
p [bar,baz,baz_provided]
end
foo(13,47)
foo(13)
foo(13,42)
This will provide the output:
[13, 47, nil]
[13, 42, true]
[13, 42, nil]
which illustrates the usage pretty well. The magic, of course, lies in the fact that default parameters are evaluated, just the same as anything else. You could do some very crazy things inside that default value specification if you wanted. Anyway, just a nugget.
