Variables and arrays

In IRB, type the following:


a = 8
b = a
puts a
=> 8
puts b
=> 8

Make sense?

Now try this:


a = 9
puts a
=> 9
puts b
=> 8

You can see that a has changed, but b has not. And this makes sense. b was assigned the value of a, not to a itself.

This is pretty close to the basic explanation I have gotten from every basic ruby textbook I have read so far. Chris Pine’s Learn to Program shows almost exactly this example.

Here’s another example:


a = "my string"
b = a
a = a + " this is"
puts a
=>"my string this is"
puts b
=>"my string"

Seems consistent, right?

So, imagine my surprise when I ran a bit of code something like this…


class MyArray
def initialize
@arry = [1,2,3]
puts "initialized"
end

attr_reader :arry

def manipulate_array
temp_arry = @arry
2.times do
temp_arry.pop
end
puts temp_arry
puts @arry
end

end

new_arry = MyArray.new
new_arry.manipulate_array

…and found that the function was emptying out both arrays!

It makes even less sense to me because I created an attr_reader for @arry. I thought this would make @arry “read only” so to speak.

I posted about it on stack overflow, and I kind of know what’s going on, but I still don’t really grok it.

Leave a Reply

Your email address will not be published. Required fields are marked *