Ruby: Can lambda function parameters have default values?
In Ruby 1.9+, you can use either of the old-style lambdas or the new "arrow" lambda syntax to set a default parameter:
ruby-1.9.1-p378 > f = lambda {|x, y=1| puts(x+y) } => #<Proc:0x000001009da388@(irb):4 (lambda)> ruby-1.9.1-p378 > f.call(1)2 => nil ruby-1.9.1-p378 > f.call(1,5)6 => nil ruby-1.9.1-p378 > f = ->(a, b=5) { puts(a+b) } => #<Proc:0x00000100a0e1b0@(irb):1 (lambda)> ruby-1.9.1-p378 > f.call(1)6 => nil ruby-1.9.1-p378 > f.call(1,2)3 => nil
In Ruby 1.8.x you can sort of fake it along the lines of:
def creator lambda do |*args| raise ArgumentError if args.empty? || args.size > 2 arg1, arg2 = args puts arg1 puts arg2 unless arg2.nil? endend>> test = creator=> #<Proc:0x000000010125e138@(irb):2>>> test.call("foo")foo=> nil>> test.call("foo", "bar")foobar=> nil>> test.call("foo", "bar", "baz")ArgumentError: ArgumentError
Edit: The above example defaults the second argument to nil
, but if you wish to have another default you can assign arg2
based on args.size
(e.g. arg2 = mydefault if args.size < 2
). Similarly if you have more than two arguments the unspecified ones will default to nil
unless you assign them yourself.
For Ruby 1.9+ see other answers.