# The evolution of a Ruby programmer
def sum(list)
total = 0
for i in 0..list.size-1
total = total + list[i]
end
total
end
def sum(list)
total = 0
list.each do |item|
total += item
end
total
end
def test_sum_empty
sum([]) == 0
end
def test_sum_one
sum([10]) == 10
end
def test_sum_several
sum([10,10,10])==30
end
def sum(list)
total = 0
list.each{|i| total += i}
total
end
def sum(list)
list.inject(0){|a,b| a+b}
end
class Array
def sum
inject{|a,b| a+b}
end
end
describe "Enumerable objects should sum themselves" do
it 'should sum arrays of floats' do
[1.0, 2.0, 3.0].sum.should == 6.0
end
it 'should sum values in sets' do
require 'set'
Set.new([1,2,3,3,3,2,1]).sum.should == 6
end
it 'should join arrays of arrays' do
[[1],[2],[3]].sum.should == [1,2,3]
end
it 'should concatenate arrays of strings ' do
['a','man','a','plan'].sum.should == 'a man a plan'.gsub(/ /,'')
end
it 'should work on hash tables, too -- appending their key/values' do
{:a => 3, :b => 4}.sum.find_all{|a| a.is_a? Numeric}.sum.should == 7
end
end
module Enumerable
def sum(zero=false)
zero ? inject(zero){|a,b| a+b} : inject{|a,b| a+b}
end
end
# Greenspun's 10th Rule of Programming version (suggested by BenD's comment)
module Enumerable
def reduce(by,zero=false)
zero ? inject(zero){|a,b| a.send(by,b)} : inject{|a,b| a.send(by,b)}
end
def sum(zero=false)
reduce(:+,zero)
end
end