Ruby variables are basically "object references" which is a sort of pointer internally. Both name
and save_name
refer to the same object both before and after your in-place modification.
Look at the result of name.object_id
and save_name.object_id
to see how this plays out, as that method is a window into what's going on internally:
name = "bob"
name.object_id
# => ...2980
save_name = name
save_name.object_id
# => ...2980
name.upcase!
name.object_id
# => ...2980
Now if you duplicate the object via a method like .dup
or .clone
, or if you create a whole new string through some other process, then it's a new object:
name = name.downcase
name.object_id
# => ...8480
Now you've got two objects in play:
name.object_id
# => ...8480
save_name.object_id
# => ...2980
These object_id
values are for all intents random but are unique per object instance. If two objects have the same object_id
value they are the same object.†
† Technically objects can override their object_id
method to return something else but this is rare.