Reputation: 11588
I've just seen this expression in a Ruby/Rails app:
def method(a, b = nil, &c)
c ||= ->(v) { v }
I understand the first part, but not the ->() { ... }
syntax. What does it mean?
The variable names have been changed for briefness. I tried searching, but the non-alphanumeric characters are obviously a nightmare for SEO.
Upvotes: 6
Views: 384
Reputation: 168101
It is a lambda literal. Put the block variables inside ()
and the body inside {}
.
->(x, y){x + y}
In the example, ->(v){v}
takes a single argument v
and returns it, in other words, it is an identity function. If a block is passed to method
, then that is assigned to c
. If not, the identity function is assigned to c
as default.
Upvotes: 6
Reputation: 19228
That is a lambda literal, introduced in Ruby 1.9:
irb> l = ->(v) { v }
# => #<Proc:0x007f4acea30410@(irb):1 (lambda)>
irb> l.call(1)
# => 1
It is equivalent to write:
irb> l = lambda { |v| v }
# => #<Proc:0x00000001daf538@(irb):1 (lambda)>
In the example you posted it is used to provide a default block to the method when none is specified, consider this:
def method(a, &c)
c ||= ->(v) { v }
c.call(a)
end
method(1)
# => 1
method(1) { |v| v * 2 }
# => 2
Upvotes: 3