Objects
Ruby is a very pure object-oriented language: all values are
objects, and there is no distinction between primitive types and object types as there are in many
other languages. In Ruby, all objects inherit from a class named
Object and share the methods defined
by that class. This section explains the common features of all objects
in Ruby. It is dense in parts, but it’s required reading; the
information here is fundamental.
Object References
When we work with objects in Ruby, we are really working with object references. It is not the object itself we manipulate but a reference to it.[*] When we assign a value to a variable, we are not copying an object “into” that variable; we are merely storing a reference to an object into that variable. Some code makes this clear:
s = "Ruby" # Create a String object. Store a reference to it in s. t = s # Copy the reference to t. s and t both refer to the same object. t[-1] = "" # Modify the object through the reference in t. print s # Access the modified object through s. Prints "Rub". t = "Java" # t now refers to a different object. print s,t # Prints "RubJava".
When you pass an object to a method in Ruby, it is an object reference that is passed to the method. It is not the object itself, and it is not a reference to the reference to the object. Another way to say this is that method arguments are passed by value rather than by reference, but that the values passed are object references.
Because object references are passed to methods, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access