Skip to content

Instantly share code, notes, and snippets.

@antonydenyer
Created April 22, 2014 12:38
Show Gist options
  • Save antonydenyer/11177414 to your computer and use it in GitHub Desktop.
Save antonydenyer/11177414 to your computer and use it in GitHub Desktop.
my inject from this morning
class Array
def skip_first?(accumulator)
return 1 if accumulator.nil?
return 0 unless accumulator.nil?
end
def my_inject(accumulator = nil)
start = skip_first? accumulator
accumulator ||= self.first
if block_given?
self[start..-1].each do |number|
accumulator = yield(accumulator,number)
end
end
accumulator
end
end
describe "my inject method" do
context 'when there is less than two elements with no initial accumulator' do
it "empty array be nil" do
expect([].my_inject).to eq [].inject
end
it "single array should return it's element" do
expect([0].my_inject).to eq [0].inject
end
end
context 'where there is 3 or more elements with no initial accumulator' do
it "uses the first element as the seed" do
sum = lambda {|sum,number| sum + number }
expect([1,2,3].my_inject &sum).to eq [1,2,3].inject &sum
end
end
context 'where there is 2 or more elements with an initial accumulator' do
it "uses the first element as the seed" do
result = [1,2,3].my_inject(100) {|sum,number| sum + number }
expected = [1,2,3].inject(100) {|sum,number| sum + number }
expect(result).to eq expected
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment