[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Delete line from file

Gavin Kistner

1/2/2007 11:47:00 PM

From: dblack@wobblini.net
> On Wed, 3 Jan 2007, William James wrote:
> > Jules wrote:
> >> And given an array of line numbers, what is the best way to delete
> >> these lines from a file?
> > lines = IO.readlines('junk1')
> > [1,3,5].each{|n| lines.slice!(n) }
>
> That's going to have a side-effect problem:
>
> irb(main):004:0> a = %w{ a b c d e f }
> => ["a", "b", "c", "d", "e", "f"]
> irb(main):005:0> [1,3,5].each {|e| a.slice!(e) }
> => [1, 3, 5]
> irb(main):006:0> a
> => ["a", "c", "d", "f"]
>
> You'd probably want to reverse the list of indices.

Or perhaps:
irb(main):001:0> a = %w{a b c d e f }
=> ["a", "b", "c", "d", "e", "f"]
irb(main):002:0> [1,3,5].each{ |e| a[e] = nil }
=> [1, 3, 5]
irb(main):003:0> a.compact
=> ["a", "c", "e"]

Remembering, of course, that the 1st line is the 0th line number.