0

In this code,

def string_assignment_original_name(name)
  save_name = name
  name.upcase!
  name
end

if name = "Bob", the output will be "BOB". Meanwhile in this code,

def string_assignment_save_name(name)
  save_name = name
  name.upcase!
  save_name
end

if name = "Bob", the output is also "BOB".

Why is this the case?

sawa
  • 165,429
  • 45
  • 277
  • 381
clockworkpc
  • 628
  • 1
  • 6
  • 16

1 Answers1

3

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.

tadman
  • 208,517
  • 23
  • 234
  • 262