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))This will provide the output:
p [bar,baz,baz_provided]
end
foo(13,47)
foo(13)
foo(13,42)
[13, 47, 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.
[13, 42, true]
[13, 42, nil]
2 kommentarer:
I had to paste this into my code editor an poke it a bit to figure out what was going on. Very neat.
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
Skicka en kommentar