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) }
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) }
->
is literal syntax, like"
. Its meaning is fixed by the language specification.Kernel#lambda
is a method just like any other method. It can be overridden, removed, overwritten, monkeypatched, intercepted, …So, semantically, they are very different.
It is also possible that their performance is different.
Kernel#lambda
will at least have the overhead of a method call. The fact that the execution engine cannot actually know whatKernel#lambda
does at runtime (since it could be monkeypatched) would also preclude any static optimizations, although I don't believe any existing Ruby execution engine statically optimizes lambda literals in any meaningful way.It's preferable, due to readibility reasons, to use new syntax
->
(introduced in Ruby 1.9) for single-line blocks andlambda
for multi-line blocks. Example:It seems a community convention established in bbatsov/ruby-style-guide.
So, in your case, would be better:
There is no difference, both returns the same
Proc
object:In my opinion,
->
is more readable.