Reputation: 111
I'm totally new to Ruby. I came across something that I'm unable to explain.
Here is my code:
arr1 = []
arr2 = [0]
5.times{
arr2[0] += 1
arr1 << arr2
}
puts "result = #{arr1}"
I was expecting the following result:
result = [[1],[2],[3],[4],[5]]
However, this is the result I'm getting:
result = [[5],[5],[5],[5],[5]]
Can someone explain to me why this happens? how I can fix it?
Many Thanks,
Upvotes: 0
Views: 77
Reputation: 773
The problem I see is that your changing the value of a mutable structure.
You keep mutating arr2 and inserting the same instance into arr1
If you trace through the execution
arr2[0] +=1 # arr1 = [], arr2 = [1]
arr1 << arr2 # arr1 = [[1]], arr2 = [1]
arr2[0] +=1 # arr1 = [[2]], arr2 = [2]
arr1 << arr2 # arr1 = [[2],[2]], arr2 = [2]
arr2[0] +=1 # arr1 = [[3],[3]], arr2 = [3]
arr1 << arr2 # arr1 = [[3],[3],[3]], arr2 = [3]
...
You can verify that it's the same instance you are inserting by doing this:
arr1.map(&:hash).uniq
Upvotes: 0
Reputation: 23317
So, you're not just adding the value of arr1 to arr2. You're actually adding arr1 itself to arr2. Then you're adding arr1 to arr2 again, now it's got the same array in there twice.
You may want to add a copy of arr1 to arr2 instead.
arr1 << arr2.dup
Upvotes: 2