Skip to content

Instantly share code, notes, and snippets.

@jeffchao
Created March 29, 2013 06:19
Show Gist options
  • Save jeffchao/5269067 to your computer and use it in GitHub Desktop.
Save jeffchao/5269067 to your computer and use it in GitHub Desktop.
Basic implementation of Enumerable.inject() in Ruby
require 'rubygems'
require 'rspec'
module Enumerable
def myinject (base = nil, &block)
return nil if block.nil?
return nil if self.length.zero?
if base.nil?
case self.first
when Fixnum then base = 0
when String then base = ''
else return nil
end
end
self.each do |e|
base = block.call(base, e)
end
base
end
end
describe Enumerable do
describe '#myinject' do
let(:arr) { Array(1..5) }
let(:arr2) { %w(a b c) }
it 'should return nil if no block exists' do
arr.myinject{}.should == nil
end
it 'should return return 15 for accumulator + element' do
arr.myinject(0){ |acc, e| acc + e }.should == 15
arr.myinject{ |acc, e| acc + e }.should == 15
end
it 'should return aabaca for accumulator + element + a' do
arr2.myinject{ |acc, e| acc + e + 'a'}.should == 'aabaca'
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment