Connecting Tech Pros Worldwide Help | Site Map

Ruby and object references / copying

Newbie
 
Join Date: Nov 2006
Location: Seattle
Posts: 16
#1: Sep 21 '07
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:

Expand|Select|Wrap|Line Numbers
  1. myVar1 = []
  2. myVar2 = myVar1
  3. myVar2 << "giggity giggity goo"
  4.  
  5. myVar[0]      # => "giggity giggity goo"
  6.  
...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:

Expand|Select|Wrap|Line Numbers
  1. class Retarded
  2.   attr_reader :var
  3.  
  4.   def initialize
  5.     @var = "mystring \n"
  6.   end
  7. end
  8.  
  9. x = Retarded.new
  10.  
  11. x.var.chomp!     # => "mystring "
  12. x.var            # => "mystring " the internal variable has changed
  13.  
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!
Expert
 
Join Date: May 2007
Posts: 213
#2: Sep 21 '07

re: Ruby and object references / copying


I have noticed the same thing. I've had programs where I wanted to play with an array, but keep the original unchanged. What I had to do was make a clone (obj.clone) and then alter the clone object. This probably doesn't help much in the way of attribute readers, but you could make a make a method to return the clone so the original isn't touched. I am by no means an expert on Ruby (still fairly new to it), so this is just my understanding. I would be interested in what others have to say, also.
Reply