Will.Whim

A weblog by Will Fitzgerald

The evolution of a Ruby programmer

# 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

Advertisements

6 responses to “The evolution of a Ruby programmer

  1. BenD June 6, 2008 at 11:26 am

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

  2. Tiffani June 6, 2008 at 4:38 pm

    Basically…

  3. Mark Nielsen June 7, 2008 at 1:19 am

    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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: