` - >`带范围的运算符

时间:2015-06-26 03:32:55

标签: ruby lambda literals

以下->运算符是什么?

scope :published, -> { where(published: true) }

scope是一种方法,:published是作为参数传递的符号,这使我相信-> { where(published: true) }构成了下一个参数。由于存在->字符,>不是有效的方法名称。

1 个答案:

答案 0 :(得分:2)

它被称为lambda literal,它只是创建lamda的一种简短方法。以下是相同的:

double = -> (x) { 2 * x }
double.call(10) # => 20

相当于:

double = lambda {|x| 2 * x }
double.call(10) # => 20

如果您不熟悉lambdas,请查看ruby-doc以获取更多详细信息http://ruby-doc.org/core-2.0.0/Proc.html#method-i-lambda-3F

此外,在StackOverflow线程What do you call the -> operator in Ruby?

之后结账