The difference between lambda and & # 8594; operator in Ruby

The following two areas 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) } 
+6
source share
3 answers

For readability reasons, it is preferable to use the 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) 

The community agreement seems to be set in the bbatsov / ruby-style-guide .

So in your case it would be better:

 scope :paid, ->(state) { where(state: state) } 
+9
source

-> is a literal syntax, for example, " . Its value is fixed by the language specification.

Kernel#lambda is a method, like any other method. It can be overridden, deleted, overwritten, neutralized, intercepted, ...

So, semantically, they are very different.

It is also possible that their performance is different. Kernel#lambda will at least have method call overhead. The fact that the runtime engine cannot really know what Kernel#lambda does at runtime (since it can be deactivated by both) also excludes any static optimizations, although I don't think that any existing ruby ​​runtime engine statically optimizes lambda literals in any meaningful way.

+4
source

It makes no difference, both return the same Proc object:

 irb(main):033:0> lambda {|x| x*x} => #<Proc: 0x007ff525b55b90@ (irb):33 (lambda)> irb(main):034:0> ->(x) {x*x} => #<Proc: 0x007ff525b7e068@ (irb):34 (lambda)> 

In my opinion, -> more readable.

+2
source

Source: https://habr.com/ru/post/981708/


All Articles