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.


2 Comments, Comment or Ping

  1. Adam

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

    December 14th, 2006

  2. evan

    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

    end

    December 14th, 2006

Reply to “Another neat trick”