Suppose I generate a class instance variable and create an accessor
function for it as follows:
class MyClass
@blah = [0,1]
def self.blah
@blah
end
end
I would like to prevent any other piece of code from having any way of
changing the value of the class variable. While the code above prevents
me from saying “MyClass.blah = ‘hello’”, it does allow me to say
“MyClass.blah[0] = ‘hello’”, which changes the value of the class
instance variable (to [‘hello’,1]) any time I try to access it in the
future.
I know that one way to fix this problem is to simple return a copy of
the instance variable instead of returning the instance variable itself,
by changing the accessor to:
def self.blah
@blah.dup
end
This way, another piece of code is still able to say “MyClass.blah[0] =
‘hello’”, but it won’t affect the results returned by “MyClass.blah” in
the future.
So this works for me, but I’m just wondering – is there a better way to
do this?