Ruby: Can lambda function parameters have default values?

asdasd picture asdasd · Sep 29, 2010 · Viewed 13.7k times · Source

I want to do something similar to this:

def creator()
        return lambda { |arg1, arg2 = nil|
                puts arg1
                if(arg2 != nil)
                        puts arg2
                end
        }
end

test = creator()

test('lol')
test('lol', 'rofl')

I get a few syntax errors:

test.rb:2: syntax error
        return lambda { |arg1, arg2 = nil|
                                 ^
test.rb:3: syntax error
test.rb:7: syntax error
test.rb:14: syntax error

is this possible in ruby? i want to set a default value for a parameter to a lambda function

Answer

Mark Rushakoff picture Mark Rushakoff · Sep 29, 2010

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