I’m trying to write a class that relies on references, so I really want
to retain the address of an object reference passed into a method. If I
simply use @lhs = lhs (lhs is passed in as an argument), how can I be
sure to just get the reference? Is there some way to just disable the
overloaded operator? What about writing a virtual method that gets self
to return a hexadecimal value of itself? Any other tricks you can think
of?
In Ruby, assignment is always by reference, and the assignment operator
cannot be overloaded. No tricks are necessary (rule of thumb: if you
need to rely on tricks, you are probably doing it wrong).
Chris Ward wrote in post #1179016:
so I really want to retain the address of an object reference
passed into a methodhow can I be
sure to just get the reference?
class Dog
attr_accessor :name
def initialize(name)
@name = name
end
end
def do_stuff(dog)
dog.name = “hello”
end
dog = Dog.new(“Sir James”)
puts dog.name
do_stuff(dog)
puts dog.name
–output:–
Sir James
hello
data = [1, 2, 3]
def do_stuff(arr)
arr << “hello”
end
do_stuff(data)
p data
–output:–
[1, 2, 3, “hello”]
- However, in ruby some objects are immutable, e.g Integers, and that
doesn’t work:
x = 1
def do_stuff(val)
val += 1
end
do_stuff(1)
puts x
–output:–
1
The line val += 1 creates a new Integer, and assigns it to the local
variable val, leaving x unaffected.