2

Would I be correct in saying that it was dangerous to use delete_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
2
  • Why do you only want to delete the first 5, rather than all of them? Commented Feb 22, 2011 at 22:02
  • The 5 is actually a place name that exists multiple times in the database. After the duplicate is detected, it is removed and replaced with a more specific name based on user selection. This is then resubmitted for any further duplicate place names clarification. I only want to do one at a time, so as the user is only asked to clarify one place name at a time. Hope that makes sense. Commented Feb 23, 2011 at 7:35

2 Answers 2

4

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...

Sign up to request clarification or add additional context in comments.

3 Comments

Not sure how your example is the same as mine? as i only want to delete the first occurrence of 5 before exiting.
Exactly. arr.index(5) finds the position of the first 5, and then arr.delete_at deletes just the element at that position. Don't confuse this with arr.delete(5), which would delete all the 5s.
Deleting while iterating isn't just fine because deleting behind your current position leads to jumping over the next one.
2

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.