torsdag, december 14, 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]

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.

2 kommentarer:

Adam sa...

I had to paste this into my code editor an poke it a bit to figure out what was going on. Very neat.

evan sa...

def foo given
  args = {:size => 5, :name => "Default"}.merge(given)

  # now
  puts "size given" if given[:size]
  # or, if you need to recognize nil
  puts "size given" if given.keys.include? :size