Re: delete_if_with_index or delete_at(array) in 1.8.6?
by Robert Klemme other posts by this author
Jul 2 2009 5:45AM messages near this date
Re: delete_if_with_index or delete_at(array) in 1.8.6?
|
Re: delete_if_with_index or delete_at(array) in 1.8.6?
2009/7/2 Bil Kleb <Bil.Kleb@[...].gov> :
> 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?
irb(main):010:0> a = %w{foo bar baz}
=> ["foo", "bar", "baz"]
irb(main):011:0> current = 1
=> 1
irb(main):012:0> a.slice! 0...current
=> ["foo"]
irb(main):013:0> a
=> ["bar", "baz"]
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
Thread:
Bil Kleb
David A. Black
Bil Kleb
James Gray
Robert Klemme
James Gray
Robert Klemme
Bil Kleb
Robert Klemme
Bil Kleb
|