Passing a lambda as a block
The trick is in using an &
which tells Ruby to convert this argument to a Proc
if necessary and then use the object as the method’s block. Starting from Ruby 1.9 there's a shortcut for lambda (anonymous) functions. So, you can write code like this:
(1..5).map &->(x){ x*x }
# => [1, 4, 9, 16, 25]
will take each element of the array and compute its power
it is the same as this code:
func = ->(x) { x*x }
(1..5).map &func
for Ruby 1.8:
(1..5).map &lambda {|x| x*x}
# => [1, 4, 9, 16, 25]
To solve your problem you can use Array's method reduce
(0
is initial value):
('A'..'K').reduce(0) { |sum,elem| sum + elem.size }
# => 11
Passing a lambda function to reduce
is a bit tricky, but the anonymous block is pretty much the same as lambda.
('A'..'K').reduce(0) { |sum, elem| ->(sum){ sum + 1}.call(sum) }
# => 11
Or you could concat letters just like this:
('A'..'K').reduce(:+)
=> "ABCDEFGHIJK"
Convert to lowercase:
('A'..'K').map &->(a){ a.downcase }
=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"]
In the context of a method definition, putting an ampersand in front of the last parameter indicates that a method may take a block and gives us a name to refer to this block within the method body.
Tack an ampersand (&
) onto the argument, for example:
("A".."K").each &procedure
This signifies that you're passing it as the special block parameter of the method. Otherwise it's interpreted as a normal argument.
It also mirrors they way you'd capture and access the block parameter inside the method itself:
# the & here signifies that the special block parameter should be captured
# into the variable `procedure`
def some_func(foo, bar, &procedure)
procedure.call(foo, bar)
end
some_func(2, 3) {|a, b| a * b }
=> 6