From: Stefano Crocco Date: 2010-10-07T05:00:59+09:00 Subject: Re: Error when using class variables with operators On Wednesday 06 October 2010, 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 @@ I truly can't understand how your code should work. However, here are some remarks: 1. have you tried following my suggestion and displaying the content of the class variables before trying the comparison? If so, are you they're not nil? 2. In the code you posted in your second message, there's no comparison between class variables. 3. It generally makes little sense to initialize class variables from the initialize method. This way, every time you create an instance of your class, the class variables are set to new values. There may be situations where this is the correct behaviour, but I think they're quite rare. Usually, in this case, instance variables are the correct choice 4. You call the off_target instance method from the on_target class method. This can't work. Either you made a mistake while writing your mail (meaning that both method are class methods or both are instance methods) or your code will fail as soon as has to execute the else clause, because off_target can only be called on an instance of your class, while in the body of the on_target? method, the implicit receiver, that is, self, is the class itself. Stefano