The evolution of a Ruby programmer

June 5th, 2008 | by Will |
# 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
  1. 6 Responses to “The evolution of a Ruby programmer”

  2. By Todd Werth on Jun 6, 2008 | Reply

    So true.

  3. By BenD on Jun 6, 2008 | Reply

    def sum(list)
    list.reduce(:+)
    end

  4. By rares on Jun 6, 2008 | Reply

    BenD +1

  5. By David Madden on Jun 6, 2008 | Reply

    LOL. So true.

  6. By Tiffani on Jun 6, 2008 | Reply

    Basically…

  7. By Mark Nielsen on Jun 7, 2008 | Reply

    A man, a plan, a canal: Panama. (it’s a palindrome, read it backwards…)

    Other than that… you lost me on this one, pal.

    Anyway, just saying hello, and advising that I blog-tagged you over at Marking Time.

    Have a good weekend.

Sorry, comments for this entry are closed at this time.