I understand pass-by-value as passing a copy of an object into a method. When a programming language is pass-by-value, we can alter that object we passed into the method, but it leaves the original object that was passed in unaffected. This is because a copy is passed into the method as opposed to the actual object itself (or a reference to that object).
I understand pass-by-reference to mean passing a reference to the actual object. Therefore: if we pass a reference of an object into a method: then when we modify the object within that method (via the reference that was passed in) then the actual object gets changed, outside of the scope of the method.
Example:
class Dog
attr_accessor :name
def initialize()
@name = "Denver"
end
end
def rename_dog(dog)
dog.name = "New_Dog_Name"
return
end
dog = Dog.new
puts "Dog's initial name: #{dog.name}" # => Dog's initial name: Denver
rename_dog(dog)
puts "Dog's New name: #{dog.name}" # => Dog's New name: New_Dog_Name
To me: this makes it seem as though ruby is pass-by-reference. We pass a reference of the dog into the rename_dog(dog)
method. Since it is a reference: we modify the actual dog object which is outside of the scope of the rename_dog(dog)
method, which is reflected by the last puts
statement.
This is as opposed to behavior I would expect if ruby was pass-by-value. If ruby was pass-by-value: I would expect that last puts
statement to return the dog.name "Denver"
as opposed to "New_Dog_Name"
.
Everywhere I look online though: everywhere says that ruby is pass-by-value. What am I getting wrong here?