From: Pit Capitain Date: 2004-08-04T04:43:47+09:00 Subject: Re: Closure question Fitzgerald,Greg schrieb: > I'm trying to make a function act as a counter, but I can't seem to get > it to work. Here's what I've tried: > > def count > counter = 1 > def count > proc {counter += 1}.call > end > counter > end > > > I was hoping for this: > count => 1 > count => 2 > count => 3 > > Instead, I got this: > count => 1 > count => NoMethodError: undefined method '+' for nil:NilClass Hi Greg, the inner def creates a new scope, so you can't access the counter variable from there. Using define_method, you can avoid creating a new scope: def count counter = 1 self.class.send :define_method, :count do counter += 1 end counter end p count # => 1 p count # => 2 p count # => 3 Regards, Pit