开发者

Using delete_at in an array loop with Ruby

Would I be correct in saying that it was dangerous to use de开发者_开发知识库lete_at while iterating through an array? How about in the following situation where after the deletion, the loop and function are exited?

arr.each_index do |i|
  if arr[i] == 5
    arr.delete_at(i)
    return
  end
end


The "danger" you're talking about comes from trying to iterate into the part of the array you're modifying. If you're only performing one modification, and exiting the iteration immediately after that, then there's no problem.

Of course, your actual example could be done much more simply as:

arr.delete_at(arr.index(5))

And on the subject of safety, it's useful to realize that you can usually delete while iterating just fine if you iterate in reverse, since in that case you're changing things behind your iteration, not ahead of it...


If you want to delete all 5s, not just the first one, you could do

new_arr = arr.reject{|x| x == 5}

Or, if you're fine with modifying the existing array,

arr.reject!{|x| x == 5}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜