252
  1. What do you call the -> operator as in the following?

    ->(...) do
      ...
    end
    
  2. Aren't the following snippets equivalent?

    succ = ->(x) {x + 1}
    succ = lambda {|x| x + 1}
    
4
  • 90
    It's annoying that you can't google "->" - good question to ask! Commented Jul 15, 2013 at 23:08
  • 11
    @Kevin you can, however, use Stack Overflow's built-in Elastic Search to search for "->": title:"->" [ruby] is:question. The key is to use the quotation marks. Commented May 29, 2014 at 21:43
  • 8
    Symbolhound can also do this: symbolhound.com/?q=-%3E+ruby Commented Jun 1, 2014 at 1:52
  • 10
    annoying or not annoying, but googling for "ruby ->" request give link to this question as first top result. Commented Feb 23, 2017 at 18:33

3 Answers 3

281

In Ruby Programming Language ("Methods, Procs, Lambdas, and Closures"), a lambda defined using -> is called lambda literal.

succ = ->(x){ x+1 }
succ.call(2)

The code is equivalent to the following one.

succ = lambda { |x| x + 1 }
succ.call(2)

Informally, I have heard it being called stabby lambda or stabby literal.

Sign up to request clarification or add additional context in comments.

Comments

144

=> == Hash Rocket

Separates keys from values in a hash map literal.


-> == Dash Rocket

Used to define a lambda literal in Ruby 1.9.X (without args) and Ruby 2.X (with args). The examples you give (->(x) { x * 2 } & lambda { |x| x * 2 }) are in fact equivalent.

6 Comments

FYI The 2 styles aren't fully interchangeable if you use do/end because of precedence rules. This prints an inspected lambda: puts -> do 1 end. This passes the block to puts, stealing it from the lambda and causing an ArgumentError: puts lambda do 1 end
Also, ruby 1.9.3's lambda literals do allow arguments.
@Kelvin that would be because Ruby tries to interpret puts lambda do 1 end as puts(lambda) do 1 end rather than puts(lambda do 1 end). The latter does in fact work - Ruby just tries to pass the block to the puts method rather than the lambda method if there's no brackets.
@PJSCopeland I'm not saying you can't get them to act the same. I'm saying they aren't 100% interchangeable syntax-wise, i.e. you can't simply do a drop-in replacement in all cases (because sometimes you need extra parentheses for lambda).
@rdurand Did you make the edit with summary "Stabby lambdas cannot accept arguments in Ruby 1.9"? This is not accurate, at least for 1.9.3 - args are allowed.
|
6

->(x) { ... } is the same as lambda { |x| ... }. It creates a lambda. See Kernel#lambda A lambda is a type of proc, one that ensures the number of parameters passed to it is correct. See also Proc::new and Kernel#proc.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.