What is -> () {} in Ruby?

I saw this expression in a Ruby / Rails application:

def method(a, b = nil, &c) c ||= ->(v) { v } 

I understand the first part, but not the syntax ->() { ... } . What does it mean?

Variable names have been changed for brevity. I tried searching, but non-alphanumeric characters are obviously a nightmare for SEO.

+6
source share
2 answers

This is a lambda literal. Place the block variables inside () and the body inside {} .

 ->(x, y){x + y} 

In this example ->(v){v} takes one argument v and returns it, in other words, it is an identity function. If the block is passed to method , then c assigned c . If not, the authentication function is assigned c by default.

+6
source

This is the lambda literal introduced in Ruby 1.9:

 irb> l = ->(v) { v } # => #<Proc: 0x007f4acea30410@ (irb):1 (lambda)> irb> l.call(1) # => 1 

This is equivalent to writing:

 irb> l = lambda { |v| v } # => #<Proc: 0x00000001daf538@ (irb):1 (lambda)> 

In the above example, it is used to provide a default block to the method, when none are specified, consider this:

 def method(a, &c) c ||= ->(v) { v } c.call(a) end method(1) # => 1 method(1) { |v| v * 2 } # => 2 
+3
source

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


All Articles