Reputation: 601
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
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:
inject
right, there's four variants.self
responds_to :[]
which isn't a promise fullfilled by all Enumerable
s.a
in your loop.yield
in preference to block.call
(it's faster)Upvotes: 3