From: "David A. Black" Date: 2010-09-12T05:57:13+09:00 Subject: Re: .each skipping elements Hi -- On Sun, 12 Sep 2010, Cameron Vessey wrote: > I have an array of links from a webpage. I need to clean up the links > so it only has city links in it. So I do a .each and test for regex. > > page.links.each{ > > if link.text =~ /(Blog|About Us|Status|Help|TOS|Privacy|Are we missing > an area?)/ > page.links.delete(link) > end > end That can't be the code you're actually running; it doesn't assign anything to the link variable. > For some reason the deleting of a link/element causes it to skip the > next link/element > > in the array the last 7 links are > > About us > Blog > Status > Help > TOS > Privacy > Are we missing an area? > > but after running the .each on the array I still end up with > > blog > help > privacy > > if I run it again > > help > > lol, so why can't I do this on just one run threw with .each? > or why would deleting an element cause it to skip the next one. > > I rebuilt it with an ugly while loop with a counter ..same problem You're doing a destructive operation on the array while you're iterating over it, which is going to give odd results. Ruby's internal counter is going to be pointing to the wrong array entry if one of them disappears. You're also doing too much work. Try this: page.links.delete_if {|link| link =~ /..../ } David -- David A. Black, Senior Developer, Cyrus Innovation Inc. The Ruby training with Black/Brown/McAnally Compleat Philadelphia, PA, October 1-2, 2010 Rubyist http://www.compleatrubyist.com