Programming Ruby p103 (Pragmatic Programmer)

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).

···

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?

Dale Martenson wrote:

puts (1…4).sum

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

Try:

puts((1…4).sum)

I guess 1.6.7 is interpreting your line as

(puts (1…4)).sum

Dale Martenson wrote:

puts (1…4).sum

This seems to work with Ruby version 1.7.2 (Windows),

But should give warning with -w, IIRC:
warning: (…) interpreted as grouped expression

but not with version
1.6.7 (Cygwin).

Old parsing of the above code is as:
(puts (1…4)).sum

Either way, puts (anything).anything_else is a bad idea in general.
Put the parenthesis in explicity.

···


([ Kent Dahl ]/)_ ~ [ http://www.stud.ntnu.no/~kentda/ ]/~
))_student
/(( _d L b_/ NTNU - graduate engineering - 5. year )
( __õ|õ// ) )Industrial economics and technological management(
_
/ö____/ (_engineering.discipline=Computer::Technology)