Ruby 中的 -> 运算符叫什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8476627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What do you call the -> operator in Ruby?
提问by Matt - sanemat
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}
您如何称呼以下
->操作员?->(...) do ... end以下片段不是等效的吗?
succ = ->(x) {x + 1} succ = lambda {|x| x + 1}
回答by kiamlaluno
In Ruby Programming Language("Methods, Procs, Lambdas, and Closures"), a lambda defined using ->is called lambda literal.
在Ruby 编程语言(“方法、过程、Lambdas 和闭包”)中,使用定义的 lambda->称为lambda 文字。
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 lambdaor stabby literal.
非正式地,我听说它被称为stabby lambda或stabby literal。
回答by Yarin
=>== 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.
用于在 Ruby 1.9.X(不带 args)和 Ruby 2.X(带 args)中定义 lambda 文字。您给出的示例 ( ->(x) { x * 2 }& lambda { |x| x * 2 }) 实际上是等效的。
回答by Douglas G. Allen
Lambda rocket
拉姆达火箭
I got that from this article. But first a google search for ruby lambda shorthand http://ruby-journal.com/becareful-with-space-in-lambda-hash-rocket-syntax-between-ruby-1-dot-9-and-2-dot-0/
我是从这篇文章中得到的。但首先谷歌搜索 ruby lambda 速记 http://ruby-journal.com/becareful-with-space-in-lambda-hash-rocket-syntax-between-ruby-1-dot-9-and-2-dot -0/
回答by Cary Swoveland
->(x) { ... }is the same as lambda { |x| ... }. It creates a lambda. See Kernel#lambdaA lambda is a type of proc, one that ensures the number of parameters passed to it is correct. See also Proc::newand Kernel#proc.
->(x) { ... }与 相同lambda { |x| ... }。它创建了一个 lambda。请参阅Kernel#lambdalambda 是一种 proc,可确保传递给它的参数数量正确。另见Proc::new和Kernel#proc。

