From: Tim Hunter Date: 2007-06-24T01:37:32+09:00 Subject: Re: Beginner's question on methods Peter Vanderhaden wrote: > I'm new to Ruby, having worked with Perl the past couple of years. I'm > having trouble calling a method to increment a counter, and I'm assuming > that the problem is with the scope of the variables? > > I'm getting the following error message: > P:/PETERV2/scripts/vlog2.rb:25:in `test_meth1': undefined method `+' for > nil:NilClass (NoMethodError) > from P:/PETERV2/scripts/vlog2.rb:47 > from P:/PETERV2/scripts/vlog2.rb:36:in `each' > from P:/PETERV2/scripts/vlog2.rb:36 > from P:/PETERV2/scripts/vlog2.rb:7:in `open' > from P:/PETERV2/scripts/vlog2.rb:7 > > This is the method I'm trying to call: > def test_meth1 > counter = counter + 1 > return counter > end > > This is the call: > > case typrec # case statement > example. > when "TR001" > cntr = test_meth1 > puts cntr # Here I want to print the counter value. > when "AB001" > ab001 += 1 > when "AI001" > ai001 += 1 > else > puts "Invalid message type" > end > > I assume that there's a really simple mistake I'm making, so any help > would be greatly appreciated. > > You never initialize the 'counter' variable so it's default value is nil. Ruby is telling you that there is no "+" method for a nil object, that is, you can't add 1 to nil. If "test_meth1" were in a class, you could make counter be an instance variable and initialize it in the initialize method. Since it's not, it'll have to be a global variable. Global variable names start with $. $counter = 0 def test $counter = $counter + 1 return $counter end -- RMagick OS X Installer [http://rubyforge.org/projects/rmagick/] RMagick Hints & Tips [http://rubyforge.org/forum/forum.php?forum_id=1618] RMagick Installation FAQ [http://rmagick.rubyforge.org/install-faq.html]