1

I understand that when we define a class variable in ruby it's preceded with @@variableName but in this code

class Hello
    @var2
    @@var3=0
    def foo1
        return @var1
    end
    def set_foo1(par1)
        @var1=par1
    end
end


I understand that var3 is a class variable and has to be initialized with some value. But what about var2? Is var2 still corresponds to an object?

When i called the program with obj1.var2=100 i get a noMethodError

Also, when i call puts Hello.var3 i get the same noMethodError

Can anyone please explain where i am getting it wrong?

lurker
  • 56,987
  • 9
  • 69
  • 103
SeasonalShot
  • 2,357
  • 3
  • 31
  • 49

2 Answers2

2

@var2 is a class level instance variable, whereas @@var3 is a class hierarchy variable.

An article about usage and differences between both of them. The important thing to remember: When you declare a class hierachy variable, it is shared between the class and all descending (inheriting) classes. This is rarely what you want.

spickermann
  • 100,941
  • 9
  • 101
  • 131
  • Thanks. In a related Topic, it makes no sense to declare a variable with a single `@` inside the class methods right? (Because a class method can only access a class variable and so we define by a double @@) – SeasonalShot Mar 18 '15 at 02:12
  • Nope. Depending on the use case it might make perfectly sense to use a class level instance variable (for example for a global state). Whereas I can hardly think about a good example for a class hierarchy variable. I would argue that a class level instance variable is always preferred over a class hierarchy variable. And the later is almost everytime a bad decision. – spickermann Mar 18 '15 at 02:17
0

Classes are objects just like any other object. Objects can have instance variables. Ergo, classes can have instance variables.

There's really nothing special about that. That's very important to understand in Ruby.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653