Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
When assigning a variable to a variable in Ruby, a reference to the object is created, not a new copy of the object. This means that the object is not copied, but rather another reference to the same object is created. This behavior is often referred to as "pass by reference".
For example, if we have the following code:
a = [1, 2, 3] b = a
Here, a and b will refer to the same object [1, 2, 3], not to its copy. Therefore, any changes we make to a will also affect b, and vice versa.
A reference to an object in Ruby is simply a reference to a location in memory where the object itself is stored. You cannot directly look at the reference, as it is an abstraction of the programming language, but you can work with it through variables that point to the object.
A reference to an object is kept in memory as long as there is at least one reference to that object. If all references to the object are removed (for example, the variable is deleted or changed to another object), then the object becomes inaccessible and can be automatically deleted by the garbage collector (garbage collector) to free up memory.
In Ruby, there is no explicit memory management, so you do not have to worry about freeing memory for objects that are no longer in use. This makes programming easier and less prone to errors related to memory management.
Using the object_id method
In Ruby, when you have an object, you cannot simply "view the reference to it," as you do not have direct access to the memory address where this object is stored. Ruby does all the memory stuff for you, so you cannot access the memory address of the object directly.
However, you can get some information about the object using the object's object_id method, which will return a unique identifier for the object as a string.
For example, if you have an object a, you can output its identifier like this:
a.object_id=> 7100 b.object_id=> 7100
Remember that b is not a separate object in memory, but a reference to another (we did this with b = a).
Note that this is not the same as "viewing the reference to the object," but simply a way to get a unique identifier for the object in Ruby. This is usually done during work to debug the code.
This post doesn't have any additions from the author yet.