20 Apr 2010, 11:18
Photo_33_pragsmall

Fred Boldireff (4 posts)

Hello Dave,

In episode 2 (00:22:15) you mention a “good use” of @class « self@ to quickly implement getter and setter of an instance variable @@count@. I get a bit confused with this example. Shouldn’t @@count@ be a class variable (@@@count@), as it reflects the state of class Dave (that is: how many instances of class Dave are instanciated)?

I have checked with a simple:

def get_count
  @count
end

… that @@count@ is indeed not accessible to instances of Dave (@get_count@ method called on those instances would return @nil@), so @@count@ does behave like a class variable (I understand it’s because it’s defined right after @class Dave@, at a point in code where the current object is the class Dave object).

But still, why do class variables (@@@count@) exist in Ruby then, and how would a @@@count@ variable compare to @@count@ ?

Anyway, a thousand thanks for this enlightening serie!

20 Apr 2010, 13:37
Dave_gnome_head_isolated_pragsmall

Dave Thomas (338 posts)

Remember that instance variables are always accessed in the object referenced by @self@. While a class is being defined (that is, inside the body of the class itself), @self@ is set to the class object. Thus instance variables set in this context are defined in the class object—they are instance variables, bit of the class, and not of instances of the class.

@@variable style class variables have a different semantics, and should be avoided.

20 Apr 2010, 14:36
Photo_33_pragsmall

Fred Boldireff (4 posts)

Thank you so much for your reply. I think I get it now, and when you write “ @@@variable@ style class variables should be avoided”, I feel like I hear your funny reruns of the sixties tv shows… Would they lead to bad coupling by any chance, and also perhaps force you to break the OO encapsulation paradigm?

Cheers, Fred.

21 Apr 2010, 13:28
Dave_gnome_head_isolated_pragsmall

Dave Thomas (338 posts)

In reality, @@class_variables don’t work very well. I’ve never felt the need for them.

23 Apr 2010, 00:08
Photo_33_pragsmall

Fred Boldireff (4 posts)

Neither did I, but I was just curious. I found an article summing up the subject (class variables vs. class level instance variables), with some interesting metaprogramming techniques that I can now decrypt thanks to your videocast. It seems the troubles arise with inheritance…

  You must be logged in to comment