Search code examples
rubyinjectenumerator

Rewriting Ruby Inject


Here is a brain bender.

I am trying to rewrite the Ruby Inject method. I have got as far as below.

class Array

  def injector(input = nil)

    if input == nil
      num = self.first
    else
      num = input
    end
    self[0..-1].each do |x|
      num = yield(num, x)
    end
    return num
  end
end

It is passing some tests, but it is not fully accurate, for example;

[1,2,3,4,5].injector(0) {|x,y| x + y} #=> 14

As opposed to the expected output 15, is it a rounding error? I cannot seem to figure this one out

Additional example (above updated [0..-1]):

[9,8,7,6,5].injector {|x,y| x * y} #=> 136080

Ruby .inject outputs 15120


Solution

  • The starting index is important as it depends on your input.

    class Array
    
      def injector(input = nil)
        if input.nil?
          start = 1
          num = self.first
        else
          start = 0
          num = input
        end
        self[start..-1].each do |x|
          num = yield(num, x)
        end
    
        return num
      end
    
    end