From: Jeremy Bopp Date: 2010-10-07T04:58:49+09:00 Subject: Re: Error when using class variables with operators On 10/6/2010 2:01 PM, Paul Roche wrote: > Stefano Crocco wrote: >> On Wednesday 06 October 2010, Paul Roche wrote: >>> |Hi. When I use class variables with operators I get the following error >>> |message........ >>> | >>> | undefined method `>' for nil:NilClass >>> | >>> | >>> |here's a piece of code that gives this error..... >>> | >>> |if @@target1 < @@target2 >>> | @@status = true >> >> It means that @@target1 is nil. Try >> >> p @@target1 >> >> just before the if and see what it shows. >> >> Stefano > > The problem is I intialise the attributes first....... > > def initialize(tar1, tar2) > @@target1 = tar1 > @@target2 = tar2 > end > > > Then I use this method.... > > def self.on_target?(mltn) > mltn.each do |trg| > if trg.target1 > trg.target2 > then p "on target" > else > off_target > end > end > end > > and call this method in the method above... > > def off_target > @@target1 = @@target1 - @@target2 > end > > So I want to make off_target accessable which is why I use @@ You don't need @@ in order to make off_target accessible. That method is already accessible from any instance of your class. What you probably mean is that you need @@ to make target1 and target2 accessible. However, the @@target1 and @@target2 variables are actually class variables shared among all instances of your class, which is probably not what you want. class MyClass def initialize(value) @@value = value end def get_value @@value end end my_class1 = MyClass.new(1) my_class1.get_value # => 1 my_class2 = MyClass.new("unexpected") my_class1.get_value # => "unexpected" What you want instead are instance variables such as @target1 and @target2. I found these notations a little hard to remember at first, but you'll find that defining class variables is pretty rare and that you can usually just use @variable. :-) -Jeremy