From: Sharon Phillips Date: 2007-11-30T21:17:02+09:00 Subject: Re: Delete array element within iterator block? On 30/11/2007, at 10:51 PM, Jari Williamsson wrote: > How do I (in an elegant way) delete an element of an array within a > block, while using a block iterator? I assume using delete_if is no good in this situation? [1,2,3,4,5,6].delete_if{|i| i>4} > [1,2,3,4] > > > The code below won't work (the wanted behavior here is to get all > array elements to print and but also delete the 2nd element after it > has been encountered): > --- > arr = [1,2,3,4] > arr.each_with_index { |e, i| > p e > arr.delete_at(i) if i == 1 > } > --- > results in: > 1 > 2 > 4 This is interesting, because although the results printed on the screen imply the 3 was removed, if you look at the array afterthe operation you'll see it was the 2 removed (as we wanted) irb(main):013:0> (a=[1,2,3,4]).each_with_index{|e,i| p e;a.delete_at(i) if i==1} 1 2 4 => [1, 3, 4] I've no ideas why Cheers, Dave > > > Of curse, I could loop and keep track of the index manually, but I'm > mainly checking if there is any built-in stuff here. > > > Best regards, > > Jari Williamsson >