Kerry - I ended up just creating a new array and adding elements to it that I do want, which works fine. Thanks for the explanation, makes sense. David - Thanks for the explanation as well. There's more code involved in the actual implementation, where the array will sometimes still contain items and sometimes be emptied in the iteration. My example was just to simplify and show the weirdness when trying to empty the array via iteration rather than just setting to [].
Thanks, James On Wed, Oct 14, 2009 at 9:31 AM, Kerry Foley <[email protected]>wrote: > > Hi James, > Strange right? Well, when you call delete within the loop it confuses > each. The first time in you delete "a". The second time in you go to the > 2nd element of the array, which is now "c" (not "b"). So you delete "c" > and are left with array => ["b"]. > > I assume you are are doing other things within the loop so one way is to > save the items you want to delete into another array i.e. to_be_deleted > and then do the deleting once you have exited the loop. > > Regards, > Kerry > > James Miller wrote: > > Hi Everyone, > > > > Wondering if someone could explain why this doesn't work as (I) > > expected... > > > > array = [ "a", "b", "c" ] > > > > array.each do |item| > > array.delete(item) > > end > > > > array => [ "b" ] > > > > Why isn't the array empty ( array => [] )? Is there a better approach? > > > > Thanks, > > James > > > > > > > > > > > > --~--~---------~--~----~------------~-------~--~----~ SD Ruby mailing list [email protected] http://groups.google.com/group/sdruby -~----------~----~----~----~------~----~------~--~---
