From: Jacob Fugal Date: 2006-06-06T05:18:14+09:00 Subject: Re: Object Troubles - undefined method `+' On 6/5/06, Paul D. Kraus wrote: > ./parse.rb:14:in `incndainvoice': undefined method `+' for nil:NilClass > (NoMethodError) > from ./parse.rb:31 > from ./parse.rb:20 > #!/usr/bin/env ruby > > class Customer > attr_reader :invoices, :ndainvoices > attr_writer :invoices, :ndainvoices > def initialize > @invoices = 1 > @ndainvoices = 0 > end > def increment_invoice > invoices = invoices + 1 > end > def increment_ndainvoice > ndainvoice = ndainvoice + 1 # this is line 14 > end > end You're problem here is that on line 14, you are actually using a local variable. This is a little tricky, since it's actually your assignment that is changing the context of the right hand side. What happens is that the parser sees "ndainvoice =" and assumes you're creating a new local variable called "ndainvoice"; this new local variable then masks the "ndainvoice" method. Since it's value is nil (the default value of an unassigned-to variable), the effect of the line is: ndainvoice = nil + 1 # ndainvoice is a local variable here In order to get ruby to recognize the assignment as a method call, rather than an assignment to a new local variable, you need to prefix "self.": self.ndainvoice = ndainvoice + 1 The reference to ndainvoice on the right hand side is correctly interpreted as a method call since there is no local variable of the same name to mask it. Alternatively, you can use the instance variable directly by prefixing an "@" (as you do in initialize): @ndainvoice = @ndainvoice + 1 As a final step, you can also use += to shorten the "a = a + b" pattern: self.ndainvoice += 1 # or @ndainvoice += 1 Incidentally, you have the same problem on line 11. Jacob Fugal