I am passing the reference of name to mod_name, I modify the referenced object from within the method but the change is not visible outside of the method, if I am referring to the same object from all locations how come the value is different depending on where I reference it?
name = "Jason"
puts name.object_id #19827274
def mod_name(name)
puts name.object_id #19827274
name = "JasonB"
end
puts name.object_id #19827274
puts name #Jason
String might be a bad example, but I get the same result even if I use a Fixnum.
As Greg mentions, in your example you’re creating a new local variable called
namethat is shadowing your parameter. This is due to behavior called copy-on-write. If you wanted the function to affect the object the parameter references, you could usereplaceinstead of doing an assignment, like this: