user2667489
user2667489

Reputation:

ruby multiple assignment not working as expected

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?

Upvotes: 0

Views: 141

Answers (3)

Farrukh Abdulkadyrov
Farrukh Abdulkadyrov

Reputation: 717

If you want 3 separate arrays, do:

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

Upvotes: 2

Akavall
Akavall

Reputation: 86128

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
=> []

Upvotes: 0

usha
usha

Reputation: 29349

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

Upvotes: 4

Related Questions