1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

What's New in Ruby 1.9.1? -The Lambda Operator

Using the Lambda Operator


The stab operator is named for its resemblance to a knife or stabbing motion: ->. Following the stab portion of the operator, there is a argument list, just as with in a normal method. Then, a normal Ruby block in braces.

Since the lambda's argument list is a formal argument list, as opposed to a block argument list, several other features such as default argument values are supported. A lambda is somewhere in between an anonymous block or closure and a formal named method.

 #!/usr/bin/env ruby
 # Assign a lambda to a variable
 l = ->(x,y){ x * y }
 # Then call it with various arguments
 puts l.call( 10, 12 )
 puts l.call( 14.44, -3.4545 )
 puts l.call( "!", 10 )
 # Declare a method that takes a callable argument
 def call_a_lambda( x, y, l )
 puts l.call( x, y )
 # Declare a lamba in the method invocation
 call_a_lambda( 10.0, 12.0, ->(x,y){ x/y } )
 # Lambdas have a formal argument list, complete with
 # default arguments
 l = ->(x,y=10){ x * y }
 # Call the new lambda with 1 or 2 arguments
 puts l.call(4)
 puts l.call('-')
 puts l.call(1.44, 23)
  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. New in Ruby 1.9.x
  6. What's New in Ruby 1.9.1? -The Lambda Operator

©2014 About.com. All rights reserved.