[英]Unintuitive behaviour of array.map
So this behaviour seems to be logical 所以这种行为似乎是合乎逻辑的
> array = (1..4).to_a
=> [1, 2, 3, 4]
> array.map {|a| [array.delete(array.first), array.delete(array.last)]}
=> [[1, 4], [2, 3]]
> array
=> []
But then when we increase the range it doesn't work: 但是,当我们增加范围时,它不起作用:
> array = (1..6).to_a
=> [1, 2, 3, 4, 5, 6]
> array.map {|a| [array.delete(array.first), array.delete(array.last)]}
=> [[1, 6], [2, 5]]
> array
=> [3, 4]
And it does the same weird behaviour with odd numbers: 而且它对奇数也有同样的怪异行为:
> array = (1..9).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
> array.map {|a| [array.delete(array.first), array.delete(array.last)]}
=> [[1, 9], [2, 8], [3, 7]]
> array
=> [4, 5, 6]
This was not what we expected, why does it behave this way? 这不是我们所期望的,为什么会这样呢?
This is a guess since I am not sure if this is the exact case but I can't put this as a comment. 这是一个猜测,因为我不确定这是否是正确的情况,但是我不能将此作为评论。
So lets go step by step: 因此,让我们逐步进行:
you defined an array: 您定义了一个数组:
> array = (1..6).to_a
=> [1, 2, 3, 4, 5, 6]
Now defined an iterator: 现在定义一个迭代器:
array.map {|a| [array.delete(array.first), array.delete(array.last)]}
so for first iteration it will take array[0]
as the value for for variable a
and do the operation and hence deleting first
and last
element of the array. 因此对于第一次迭代,它将采用
array[0]
作为变量a
的值并执行操作,因此删除了数组的first
和last
元素。
After first iteration array
becomes [2,3,4,5]
. 在第一次迭代之后,
array
变为[2,3,4,5]
。
For second iteration it will take array[1]
as the value for for variable a
and do the same as in first iteration and delete first and last element. 对于第二次迭代,它将采用
array[1]
作为变量a
的值,并且与第一次迭代相同,并删除第一个和最后一个元素。 Now array
is [3,4]
. 现在
array
是[3,4]
。
Now for 3rd iteration, well it would not have tried for 3rd iteration if your original array was only size of 2 ie like [2,3]
but since you modified your original array during iteration so it will attempt 3rd iteration since original array had length 6
. 现在对于第三次迭代,如果原始数组的大小仅为2,即
[2,3]
,那么它就不会尝试第三次迭代,但是由于您在迭代过程中修改了原始数组,因此由于原始数组具有长度,因此它将尝试第三次迭代6
。
For 3rd iteration it needs array's third element ie array[2]
but your current array does not have that index so it returns the remaining array without any other operation. 对于第3次迭代,它需要数组的第三个元素,即
array[2]
但是您当前的数组没有该索引,因此它无需执行任何其他操作即可返回剩余的数组。
It is really confusing to modify array while being iterated. 在迭代时修改数组确实令人迷惑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.