Lambda和->之间的区别Ruby中的运算符 [英] Difference between lambda and -> operator in Ruby
本文介绍了Lambda和->之间的区别Ruby中的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下两个作用域产生相同的结果,哪种语法更可取,还有其他区别吗?
The following two scopes generate the same result, which syntax is preferable and is there any other difference?
scope :paid, lambda { |state| where(state: state) }
scope :paid, ->(state) { where(state: state) }
推荐答案
由于可读性原因,最好对单行代码使用新语法->
(在Ruby 1.9中引入),对多行代码使用lambda
线块.示例:
It's preferable, due to readibility reasons, to use new syntax ->
(introduced in Ruby 1.9) for single-line blocks and lambda
for multi-line blocks. Example:
# single-line
l = ->(a, b) { a + b }
l.call(1, 2)
# multi-line
l = lambda do |a, b|
tmp = a * 3
tmp * b / 2
end
l.call(1, 2)
似乎在 bbatsov/ruby-style-guide中建立的社区约定.
因此,根据您的情况,会更好:
So, in your case, would be better:
scope :paid, ->(state) { where(state: state) }
这篇关于Lambda和->之间的区别Ruby中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文