Reputation: 5618
What do you call the ->
operator as in the following?
->(...) do
...
end
Aren't the following snippets equivalent?
succ = ->(x) {x + 1}
succ = lambda {|x| x + 1}
Upvotes: 250
Views: 75910
Reputation: 110685
->(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.
Upvotes: 6
Reputation: 29679
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.
Upvotes: 280
Reputation: 183569
=>
== Hash RocketSeparates keys from values in a hash map literal.
->
== Dash RocketUsed 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.
Upvotes: 143