0

I am trying to do something like this:

a = b = c = []

a << 1

Now I am expecting that b and c will be an empty array, whereas a will have one element. But its not working like that, here b and c also contains the same element, how is it working like this?

2
  • 3
    That is because a, b, and c all refer to the same array. Commented Jun 16, 2014 at 18:59
  • 2
    This is not what the term multiple assignment usually refers to. Multiple assignment is of the form a, b = c, d. Commented Jun 16, 2014 at 19:45

3 Answers 3

4

When you do this

a = b = c = []

All three variables point to the same location in memory. They are three references to same location in memory

So when you do

a << 1, you are writing to the memory space referred by all three variables

Sign up to request clarification or add additional context in comments.

2 Comments

OP can do a.object_id, b.object_id, ... to see this more clearly.
@Akavall but when we are assigning a = b = 0, and checking the a.object_id and b.object_id then also they are coming same but their is totally different from a = b = []
2

If you want 3 separate arrays, do:

a, b, c = [], [], []

2 Comments

This is likely what the OP meant to do. Though, technically it doesn't answer his question.
Okay I see what you mean, you are right. @Vimsha has already explained it so didn't want to duplicate the answer, just gave a solution
0

You can use .dup to create an object with same value at different memory location.

Here is your example without c because it is irrelevant.

irb(main):028:0> a = b = []
=> []
irb(main):029:0> a.object_id #a and b refer to the same location in memory
=> 19502520
irb(main):030:0> b.object_id
=> 19502520
irb(main):031:0> b = a.dup
=> []
irb(main):032:0> b.object_id #b refers to different location in memory
=> 18646920
irb(main):033:0> a << 1
=> [1]
irb(main):034:0> b
=> []

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.