As an experiment, I wrote some code that looks like
class MyClass
@var = 100
def hello
p "hello"
end
end
I know that if I do MyClass.new that @var is not defined on that object, rather I think this would define @var on the class MyClass.
Is there a practical usage to this?
It does have a use: Class variables. The normal Ruby class variable implementation,
@@, shares the same variable between a superclass and its subclasses:Obviously, this is pretty useless (except for the fact that, unlike class instance variables, class variables are also accessible directly in instance methods, as opposed to through
self.class). But the same example with class instance variables:Also, class instance variables can harness all of the metaprogramming already written for instance variables, like so: