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.
In Ruby, the at-sign ( @ ) before a variable name (e.g. @variable_name ) is used to create a class instance variable.
$! refers to the last error that was raised, and is useful in lots of different contexts such as Rake tasks.
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.
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.
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.
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!"
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With