Ruby is a great language because some tasks can be achieved in different ways.
The way you choose can be the most readable and beautiful.
Today I want to show you different ways to do a sum on values returned from different methods.
def negative
25
end
def positive
25
end
def neutral
50
end
The result that we want is this:
(negative + positive + neutral)
# => 100
First way: collect all the values in an array and then inject + on it. (http://apidock.com/ruby/Enumerable/inject)
%w(negative positive neutral).collect{ |m| send(m) }.inject(:+)
# => 100
Or: pass to the inject method the values that we want sum to be initialized, in this case 0, and a second variable m as the method name.
%w(negative positive neutral).inject(0) {|sum, m| sum + send(m) }
# => 100
That’s all!
Design by Simon Fletcher. Powered by Tumblr.
© Copyright 2010