What do you call the -> operator in Ruby?

RubySyntax

Ruby Problem Overview


  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}
    

Ruby Solutions


Solution 1 - Ruby

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.

Solution 2 - Ruby

=> == 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.

Solution 3 - Ruby

->(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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt - sanematView Question on Stackoverflow
Solution 1 - RubyapadernoView Answer on Stackoverflow
Solution 2 - RubyYarinView Answer on Stackoverflow
Solution 3 - RubyCary SwovelandView Answer on Stackoverflow