Hey guys,
I had a theoretical question about Ruby's object handling. Not that it really matters, but I'm using Ruby 1.8.6.
In Ruby, every variable holds a reference to an object. For instance, if you were to say:
-
myVar1 = []
-
myVar2 = myVar1
-
myVar2 << "giggity giggity goo"
-
-
myVar[0] # => "giggity giggity goo"
-
...the result is that the Array object referenced by both variables (it's the same object after all) would hold a new element.
However, this creates an interesting dilemma with regards to attribute readers, because technically, you can modify what should be a protected object. Normally this isn't a problem, but in the case that the object has mutating/destructive methods, they can be used. Consider the following class:
-
class Retarded
-
attr_reader :var
-
-
def initialize
-
@var = "mystring \n"
-
end
-
end
-
-
x = Retarded.new
-
-
x.var.chomp! # => "mystring "
-
x.var # => "mystring " the internal variable has changed
-
Is there any idiomatic way to avoid this problem, or do we all just live with it, hoping it won't matter in the end?
Thanks!