开发者

Will array.each work properly if the array is updated during each iteration?

Will the method to process each element of an Array properly do that if the array is being updated within the code block of the each loop?

For e开发者_StackOverflow社区xample:

arr.each do |x|
  if (x != 2)
    arr.push(x+4)
  end
end

Will the loop still iterate over every element within the array, even though it is being lengthened?


Maybe


Yes, if you are talking about MRI, and the question is: "Will the iterator traverse my new elements?".

If you are talking about Ruby as a language, "maybe". There is no specification so MRI serves as the reference implementation.

But having said that, this just seems like something that would be implementation-specific, partly because requiring any specific behavior would impose a constraint on implementations for no clear benefit, but with certain performance trade-offs.

It's also quite imperative, so it's perhaps not "the Ruby way", which leans more to functional styles.

Here is how I think a good Ruby program should write that sort of loop. This expression will return the old array a unless it changes, in which case it creates a new array in a functional style so there is never any doubt about what the result will be...

>> a = [1, 2, 3]
=> [1, 2, 3]
>> a.inject(a) { |m, e| e < 99 ? m + [99] : m }
=> [1, 2, 3, 99, 99, 99]

A faster (if lots of new elements are added) semi-functional expression would be:

t = a.inject(a.dup) { |m, e| e < 99 ? m << 99 : m } 


Yes, it will keep looping until it reaches the end of the array which will probably never happen since it keeps getting new entries with every iteration.

So I would strongly suggest against you current code since you will probably be stuck in an infinite loop.

Not sure exactly what you are going for, however this code would be much better since it has a clear ending:

arr.each do |x|
  if x < 2
    arr.push x + 4
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜