Variable types in Ruby

What is the difference between a class instance variable and an object variable in Ruby?

 5
Author: poketulhu, 2015-10-24

5 answers

First, an object is an instance of a class. This is the same concept. You can also often find the word "instance", which also means "instance of a class".

Secondly, in addition to the instance -, and class-variables, there is another interesting thing - the class-instance variable (or instance-variable of the class level).

They are similar to class variables. But if class variables share the value of and for classes inherited from the current one, then instance class variables are only for a specific class, and are not inherited. (they are the preferred solution if there is no need to share the variable with the inheritors).

The trick is that in ruby, any declared class is an instance of the Class class. And these same objects of the Class class can also have their own instance methods (of the class level).

By the way: any object in ruby (including a class) is an instance of the Object class. Hence the expression "a class is an object, and an object is a class".

 3
Author: Фил, 2017-06-14 21:45:01

Each class is an instance of type Class and each class is a subclass of type Object (in 1.8-in 1.9, each class is a subclass of BasicObject'a). Thus, each class is an object in the sense that it is an instance of a subclass of Object, i.e., a class. In other words, there is no difference between the perm of a class and an object.

 2
Author: Мстислав Павлов, 2015-10-24 08:18:28

The value of the instance variable is only available to inside the instance to which it belongs.

 0
Author: BadAllOff, 2015-10-30 00:42:59

No different, since the object is an instance of the class

 0
Author: Biscar, 2017-06-15 14:23:41

Your 5 kopecks.. ) As far as I understand, we are talking about an instance of the class and an object of the class.

An object of a class (read class) is a kind of "framework" on which to build instances of the class..

For example, class object variables are shared by all instances of the class..

Class SomeClass #SomeClass is an object of the class (the actual framework)

@@class_var = -10 # this is a variable of a class object (or just a class) it has
#one value for all instances of the class and everyone can change it

def initialize(x,y)
@x,@y = x, y #these are class instance variables, each instance has its own variables
# and have their own values for each instance of
end

End

Some_obj = SomeClass.new(-1,-1) #some_obj is an instance of class @x, @y = -1,-1
and @@class_var = -10
some_obj_next = SomeClass.new(-2,-2) #some_obj_next is an instance of class @x, @y = -2,-2
and @@class_var = -10(because it a common class object variable for all )

 0
Author: hend, 2017-08-15 12:19:57