On Dec 11, 1:09 pm, clouder <clouder... / gmail.com> wrote:
> I had some time wrapping my head around this one messing with irb
>
> I was wondering why b.compact! would change the value of a
>
> As i continually tried doing
> a = [1,2,3]
> b = a
> b = [1,3,4]
> and was getting a => [1,2,3] and b => [1,3,4]
>
> After trying with strings and gsub and such it finally dinged that b=a
> has assigned 'b' to the object stored in 'a', so running a method on
> it was effecting the object stored in both 'a' and 'b'.  Where as when
> I was doing b = [1,3,4] it was creating a new object all together so
> 'a' was never effected.  Is this correct?

You've got it! Assigning to a variable is like moving a sticky note
with the name of that variable onto an object floating in space.
Reading the 'value' of a variable is like finding the sticky note with
that variable on it and instead grabbing the object underneath.

So, when you write "a = [1,2,3]", you're creating a new Array object
floating in space, and then slapping a sticky note on it.

When you then write "b = a", you're finding that Array floating in
space, and slapping another sticky note next to the one that says "a".

If you then say "b.compact!", you are telling the Array that 'b'
refers to to compact itself, which, of course, is the same Array as
'a' is refering to.

If instead you say "b = [1,3,4]" then you're taking the 'b' sticky
note off of the first Array, and sticking it on the new array that you
just created.

> If so, sorry for making a
> dumb post if everyone else git this :X  I thought I'd post it anyways
> to possibly help some poor soul like me struggling over why this might
> not work as expected.

Don't apologize - references confuse a lot of new users, who often
think of a variable as a 'shoebox' into which objects are stuffed,
instead of lightweight references. There have been a few in-depth
threads about this in the past, but it still bears repeating to help
all readers who might not have read those discussions.