Programming Ruby p103 (Pragmatic Programmer)

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?
Thanks.

Jim

Jim Bartlett wrote:

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?
Thanks.

Let me take a wild guess: You’re using puts or print to print the value
and write:
puts (1…4).sum
or something similar? The puts assumes the parenthesis as its argument
list, and what is returned by puts (nil) is the object that gets the sum
message. Try extra parenthesis.
puts ((1…4).sum)

···


([ 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)

That was it. I was using puts (1…4).sum. I appreciate all the input from
everyone. Thanks for your help!

Jim.

“Kent Dahl” kentda@stud.ntnu.no wrote in message
news:3D94A298.E3578167@stud.ntnu.no…

Jim Bartlett wrote:

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?

···

Thanks.

Let me take a wild guess: You’re using puts or print to print the value
and write:
puts (1…4).sum
or something similar? The puts assumes the parenthesis as its argument
list, and what is returned by puts (nil) is the object that gets the sum
message. Try extra parenthesis.
puts ((1…4).sum)


([ 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)