What is a class instance variable?

Questions by scott   answers by scott

Showing Answers 1 - 15 of 15 Answers

hari

  • Feb 3rd, 2012
 

i think , class variable i.e;static and instance variables i.e;non-static are there .but there is no class instance variable.

  Was this answer useful?  Yes

Satya

  • Mar 11th, 2013
 

There is nothing called Class instance variables but there are Class variables that are shared by all the instances of a Class. Every Class variable is declared preceded by @@.

Code
  1. class SomeClass

  2.         @@no_of_instances = 0

  3.         .....

  4.         ...

  5.         ..

  6. end

  Was this answer useful?  Yes

karmue

  • Apr 1st, 2013
 

there's no class instance variable but there is instance variable and class variable, or global variable @variable is shared in the defined instance

@@variable is shared for all instances of this class
and also you need attr_accessor to enable access from outside

  Was this answer useful?  Yes

Nox

  • Feb 25th, 2014
 

There is a thing called class instance variable. Since any Ruby class is in fact object, you can define instance variables for it. It is generally advised to use @class_instance_variable on a class instead of a @@class_variable, when you dont want class data to be shared with descendants.

Code
  1. class BaseClass

  2.   @class_instance_variable = :just_defined_a_class

  3.   @@class_variable = :base_class

  4.  

  5.   def self.check_class_variables

  6.     puts @class_instance_variable

  7.     puts @@class_variable

  8.   end

  9. end

  10.  

  11. BaseClass.check_class_variables

  12. #Prints

  13. # just_defined_a_class

  14. # base_class

  15.  

  16. class DescendantClass < BaseClass

  17.   @class_instance_variable = :just_defined_descendant_class

  18.   @@class_variable = :descendant_class

  19. end

  20.  

  21. DescendantClass.check_class_variables

  22. #just_defined_descendant_class

  23. #descendant_class

  24.  

  25. #But

  26. BaseClass.check_class_variables

  27. #just_defined_a_class

  28. #descendant_class

  29.  

  30.  

  Was this answer useful?  Yes

Dwaraka

  • Dec 18th, 2014
 

No. Please refer to answer given by Nox. When a variable is defined within the body of the class its called Class Instance Variable. It is like class variable but cannot be inherited. Usual use case is for setting up configuration files and is not unique for its subclasses.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions