The trick is to use & , which tells Ruby to convert this argument to Proc , if necessary, and then use this object as a block of methods. Starting with Ruby 1.9 there is a shortcut for lambda (anonymous) functions. So you can write the code as follows:
(1..5).map &->(x){ x*x }
will take each element of the array and calculate its power
this 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}
To solve your problem, you can use the Array reduce method ( 0 is the initial value):
('A'..'K').reduce(0) { |sum,elem| sum + elem.size }
Passing a lambda function to reduce bit complicated, but the anonymous block is almost the same as the lambda.
('A'..'K').reduce(0) { |sum, elem| ->(sum){ sum + 1}.call(sum) }
Or you can write lines 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, placing an ampersand in front of the last parameter indicates that the method can take a block and gives us a name to refer to this block inside the method body.
Tombart Mar 21 '14 at 21:55 2014-03-21 21:55
source share