0

Explain please, I can not understand.

class Foo
  @a = 123
  @@b = 123
end

What are the advantages of variable objects-classes and the class variables? When should I use first, and in which the second?

2 Answers 2

4

Instance level variables area created anew for each instance of the class. For example, a variable @id should probably be unique for each instance of Foo. However, there may be some values that should be the same for every instance of the type. In that case, a class variable would be more appropriate.

One important side effect of class level variables is that they are shared amongst derived classes as well. This means that changing the value in a subclass of 'Foo' will change it for 'Foo' objects as well. This may be what you want, but it can be a bit surprising to find out the hard way.

For example:

class Foo
  @@some_var = 1
  def bar
    puts(@@some_var)
  end
end

class Baz < Foo
  def perhaps_unexpected
    @@some_var = 10
    Foo.new.bar  #prints '10'
  end
end
Sign up to request clarification or add additional context in comments.

2 Comments

This code prints 3 and nil. Why? codeclass MyClass @@global = 3 @local = 7 def my_print puts @@global puts @local end end obj = MyClass.new obj.my_printcode
Because you cannot initialize member variables in the class scope, you need to do it inside of a method (usually the constructor, initialize). From the docs: An instance variable has a name beginning with @, and its scope is confined to whatever object self refers to. In your code self does not refer to that class scope, so the variable is uninitialized.
1

Use a class variable when you want all the instances of the class to share that variable, and use an instance variable when you want each instance to have its own non-shared variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.