0

Recently I attempted to append a number to one of the nested arrays in my script. I expected only the nested array at the specified index to have the number appended to it, but what actually happened was that all of the nested arrays had the number appended to them.

This behaviour seems very odd, why do ruby arrays function this way?

irb(main):001:0> [1,2,3].push 3 
=> [1, 2, 3, 3]
irb(main):002:0> layered = [[]] * 5
=> [[], [], [], [], []]
irb(main):003:0> layered[0] << 2
=> [2]
irb(main):004:0> layered
=> [[2], [2], [2], [2], [2]]
irb(main):005:0> 

1 Answer 1

4

Because all of them are the same array. You can check it by calling Object#object_id on each element:

[3] pry(main)> layered = [[]] * 5
=> [[], [], [], [], []]
[4] pry(main)> layered[0].object_id
=> 70207042910540
[5] pry(main)> layered[1].object_id
=> 70207042910540
[6] pry(main)> layered[2].object_id
=> 70207042910540

To create new array for each element then use Array.new(5) { [] }.

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

2 Comments

Thank you so much!! This seems a little confusing as to why [ [] ] * 5 would do this. Do you know of any practical examples of when using [ [] ] * 5 would be appropriate?
When you will replace whole array at assign (as you should do). So if you replace layered[0] << 2 with layered[0] += [2] then it should work.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.