Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is ->() { } in Ruby?

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.

like image 960
hohner Avatar asked Sep 19 '13 08:09

hohner


People also ask

What does @variable mean in Ruby?

In Ruby, the at-sign ( @ ) before a variable name (e.g. @variable_name ) is used to create a class instance variable.

What is $! In Ruby?

$! refers to the last error that was raised, and is useful in lots of different contexts such as Rake tasks.

What is a ruby?

Main ruby producing countries A ruby is a pink to blood-red colored gemstone, a variety of the mineral corundum (aluminium oxide). Other varieties of gem-quality corundum are called sapphires. Ruby is one of the traditional cardinal gems, together with amethyst, sapphire, emerald, and diamond.

What are the operators in Ruby?

Ruby supports a rich set of operators, as you'd expect from a modern language. Most operators are actually method calls. For example, a + b is interpreted as a.+(b), where the + method in the object referred to by variable a is called with b as its argument.

What is Ruby programming language?

More specifically, Ruby is a scripting language designed for front- and back-end web development, as well as other similar applications. It’s a robust, dynamically typed, object-oriented language, with high-level syntax that makes programming with it feel almost like coding in English.

How do you call a method in Ruby?

In Ruby, methods are built-in abilities of objects. To access an object’s methods, you need to call it using a . and the method name. Strings in Ruby are a sequence of characters enclosed by single quotation marks (‘’) or double quotation marks (“”). s1 = 'I am a single string!' s2 = "I am a double string!"


2 Answers

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.

like image 171
sawa Avatar answered Oct 04 '22 05:10

sawa


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
like image 25
toro2k Avatar answered Oct 04 '22 05:10

toro2k