Wednesday, October 31, 2012

15-second Guide to Ruby Lambdas

Pre-Ruby 1.9.1 syntax that still works in 1.9.3:

$ irb
1.9.3p194 :001 > a = lambda {Time.now}
 => # 
1.9.3p194 :002 > a.call
 => 2012-10-31 11:39:46 -0400 
1.9.3p194 :003 > a = lambda {|b| b + 5}
 => # 
1.9.3p194 :004 > a.call 5
 => 10 
1.9.3p194 :005 > a = lambda {|b,c| b*c}
 => # 
1.9.3p194 :006 > a.call 5,6
 => 30 
1.9.3p194 :007 > a = -> {Time.now}
 => # 
1.9.3p194 :008 > exit

Ruby 1.9.1+ syntax (remember: 1. stabby lambda is like a method definition; there is no whitespace between the -> and the left parenthesis. 2. for a stabby lambda with more than one argument, you must define the lambda with the arguments in parentheses.):

$ irb
1.9.3p194 :001 > a = -> {Time.now}
 => # 
1.9.3p194 :002 > a.call
 => 2012-10-31 11:41:46 -0400 
1.9.3p194 :003 > a = -> b {b + 5}
 => # 
1.9.3p194 :004 > a.call(5)
 => 10 
1.9.3p194 :005 > a.(5)
 => 10 
1.9.3p194 :006 > a = ->(b) {b + 5}
 => # 
1.9.3p194 :007 > a.call(5)
 => 10 
1.9.3p194 :008 > a.(5)
 => 10 
1.9.3p194 :009 > a = ->(b,c) {b*c}
 => # 
1.9.3p194 :010 > a.call 5,6
 => 30 
1.9.3p194 :011 > a.(5,6)
 => 30 

Note that {...} are blocks, so you can do; ...; end instead:

$ irb
1.9.3p194 :001 > e = ->(m,c) do
1.9.3p194 :002 >     m * c ** 2
1.9.3p194 :003?>   end
 => # 
1.9.3p194 :004 > e.(5,2)
 => 20 

No comments: