lundi 13 avril 2015

Storing array into another array, getting an unexpected result?

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,


Aucun commentaire:

Enregistrer un commentaire