What do you call the
->operator as in the following?->(...) do ... endAren't the following snippets equivalent?
succ = ->(x) {x + 1} succ = lambda {|x| x + 1}
3 Answers
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.
Comments
=> == 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
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 endputs 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.lambda).->(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.
"->":title:"->" [ruby] is:question. The key is to use the quotation marks.