Ruby and object references / copying

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • beatTheDevil
    New Member
    • Nov 2006
    • 16

    Ruby and object references / copying

    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:

    [code=ruby]
    myVar1 = []
    myVar2 = myVar1
    myVar2 << "giggity giggity goo"

    myVar[0] # => "giggity giggity goo"
    [/code]
    ...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:

    [code=ruby]
    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
    [/code]

    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!
    Last edited by beatTheDevil; Sep 21 '07, 05:48 AM. Reason: ...forgot to finish a sentence
  • improvcornartist
    Recognized Expert Contributor
    • May 2007
    • 303

    #2
    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.

    Comment

    Working...