Robin Winton
Robin Winton

Reputation: 601

Rewrite the inject method in ruby

How would one go about rewriting the inject method but in ruby, basically to have

(5..10).inject { |sum, n| sum + n }  == (5..10).new_inject { |sum, n| sum + n }

evaluate to true. That is without using method_missing...

EDIT:

As requested, this is what I've got so far:

module Enumerable
  def new_inject(&block)
    if block_given?
      a ||= self.first
      self[1..-1].each do |s|
        @result = block.call(a,s)
      end
    end
    @result
   end   
end

Upvotes: 0

Views: 810

Answers (1)

dbenhur
dbenhur

Reputation: 20408

Excellent examples of pure Ruby implementations of most of the Ruby stdlib can be found in Rubinius; here's inject

In your attempt I spot several mistakes:

  1. You don't have the signature of inject right, there's four variants.
  2. Your assuming that self responds_to :[] which isn't a promise fullfilled by all Enumerables.
  3. You've failed to update your accumulator a in your loop.
  4. You should use yield in preference to block.call (it's faster)

Upvotes: 3

Related Questions