From: "David A. Black" Date: 2009-07-02T21:55:10+09:00 Subject: Re: delete_if_with_index or delete_at(array) in 1.8.6? Hi -- On Thu, 2 Jul 2009, Bil Kleb wrote: > Hi, > > Given an array of integers, I need to delete all those > entries that are lower than the current array index. > > I first thought of the non-existent, > > array.delete_if_with_index{ |e,i| e < i } > > then, > > remove_indices = [] > array.each_with_index{ |e,i| remove_indices << i if e < i } > array.delete_at( remove_indices ) > > or the same, but with a fictious inject_with_index, > > remove_indices = inject_with_index([]){|acc,e,i| acc << i if e < i } > array.delete_at( remove_indices ) > > and finally the 1.9 possibility, > > array.map_with_index!{ |e,i| e < i ? nil : e }.compact! > > before compromising with > > array = (0...array.size).zip(array).map{ |i,e| e < i ? nil : e }.compact > > Anything more elegant available? > > Or perhaps an alternative way to attack the problem? In 1.9 I would do: >> a = [0,1,2,1,4,3,6,7,2] => [0, 1, 2, 1, 4, 3, 6, 7, 2] >> a.reject!.with_index {|e,i| e < i } => [0, 1, 2, 4, 6, 7] In 1.8 I'm not coming up with anything more elegant than: >> a.values_at(*(0...a.size).reject {|i| a[i] < i }) => [0, 1, 2, 4, 6, 7] or some variant thereof. David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Now available: The Well-Grounded Rubyist (http://manning.com/black2) "Ruby 1.9: What You Need To Know" Envycasts with David A. Black http://www.envycasts.com