I am trying to return a subset of a multi-dimensional array, trying to keep the exact structure of dimensions, but.. something strange is happening... take a look please:
space = [ [ [1],[2],[3] ], [ [4],[5],[6] ], [ [70],[8],[9] ] ]
space_subset = space[(1..2)].collect { |y| y[1] }
=> [[5], [8]]
Let's break it down:
space[(1..2)]
=> [ [ [4], [5], [6] ], [ [70], [8], [9] ] ]
so now I can be sure what I am calling .collect on
in fact:
[ [ [4], [5], [6] ], [ [70], [8], [9] ] ].collect { |y| y[1] }
=> [[5], [8]]
Then... (for the real question)...
If now space_subset is [[5], [8]]
and I try to modify it like this:
space_subset[1].delete (8)
and as expected I get: => [[5], []]
why does this at the same time modifies the original "space" array from which I extracted the subset array ?
If now I do:
space
=> [[[1], [2], [3]], [[4], [5], [6]], [[70], [], [9]]]
"8" is missing, the same value I deleted from the space_subset
I am looking at ruby Array api docs and from what I am reading my code should work without surprises... but.. still.....
Can you help me figure what I'm doing wrong, or misunderstanding here ?
Thanks to everyone who takes the time to answer
space_subsetcontains the reference to both[5]and[8]arrays, not their values. So if you alter it inspace_subset, it will affectspaceas well.