variable pointers

Explain why b is still “hello”.

a = "hello"
b = a
a = "hi"
a << " world"

puts a # hi world
puts b # hello

b is still “hello” because when you declared `b = a`, ruby had that variable b point to the actual memory location of a. It makes sense to save memory and just point to that space.

Once you reassigned `a = “hi”` what happens now is that a is given its own location in memory since a is being reassigned. so now a would give you ‘hi’ and b would give you ‘hello’. notice there are 2 different memory locations now, one holding the value or variable b the other for variable a value. If you check the object ids for each variable you will notice they are different.

Then we did `a << ” world”` this just mutated and appended the string ” world” to a. SO now we get for a, “hi world”, and b gives us “hi”
This is an example of variable pointers.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: