Jim Bartlett wrote on Friday, September 27, 2002 12:43 PM
> I created the "Inject" module as shown in Programming Ruby, p102-103 and
> included it in the Range class. When I try to get the sum of a range (ie
> (1..4).sum), it just spits out 1..4 and then an error:
> 
> undefined method "sum" for nil (NameError)
>
> It works fine for arrays when included in class Array. What have I missed?

Do you mean like this?

module Inject
  def inject(n)
    each do |value|
      n = yield(n, value)
    end
    n
  end
  def sum(initial = 0)
    inject(initial) { |n, value| n + value }
  end
  def product(initial = 1)
    inject(initial) { |n, value| n * value }
  end
end

class Range
  include Inject
end

puts (1..4).sum

This seems to work with Ruby version 1.7.2 (Windows), but not with version
1.6.7 (Cygwin).