How Ruby variables reference objects

In general, Ruby variables hold references to objects and do not hold values. In the following example, variable_one and variable_two both reference the “happy” object.

variable_one = "happy"
variable_two = variable_one

Screen Shot 2013-09-29 at 2.28.05 PM

If the “happy” object is mutated, then both variable_one and variable_two will point to the same object, but it will have a different value (because it has been mutated). variable_one and variable_two can both be used to send messages to the “happy” object. In the following code, we use the variable_two reference to the “happy” object to mutate the object and observe that variable one will also reference the updated object.

>> puts variable_two
>> puts variable_one

Screen Shot 2013-09-29 at 3.06.05 PM

When variables are reassigned, all previous references are destroyed. If the variable_two is reassigned to the object “aight”, the old reference to “HAPPY” is broken and variable_two can only be used to send messages to the “aight” object.

Screen Shot 2013-09-29 at 3.07.55 PM

Some Ruby objects are global values are the only instance of their respective class such as true, false, and nil. Other classes make multiple objects, but there is only one per type of object. For example, the Symbol class only makes one :bob object and the Integer class only makes one 100 object. These objects are stored in variables as values, which explains why some common operations available in other programming languages are not available in Ruby. This syntax does not work:

>> x = 1
>> x++

The variable x stores the value of 1, not a reference to 1, so x++ is logically equivalent to 1++. We cannot change the 1 object to the 2 object (or else we would no longer have access to the 1 object), so this syntax is invalid.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s