Short lambda syntax in Ruby 1.9

Ruby 1.9 brings a shorter way to define lambdas using the -> operator:

twice = -> (x) { 2 * x }
twice.call(5) # => 10

This is equivalent to:

twice = lambda {|x| 2 * x }
twice.call(5) # => 10

Note that the syntax is subtly different from Coffeescript where you define function parameters before the arrow: (x) -> { 2 * x }.

Henning Koch about 8 years ago
This website uses short-lived cookies to improve usability.
Accept or learn more