From: Tim Hunter Date: 2008-11-16T02:27:45+09:00 Subject: Re: IO#lineno= doesn't work the way I expected Chad Perrin wrote: > I'm working on something that operates on each line of a file > individually. So far, the relevant part looks something like this: > > in_fh = File.open(infile, 'r') > out_fh = File.open(outfile, 'w') > > in_fh.each_line do |l| > out_fh << l > end > > Obviously not the actual working code (since it doesn't do anything other > than copy the file), but it's the simplified version I'm using to test a > feature, anyway. > > This works exactly as expected. I get a duplicate of the input file, > with the name assigned to the outfile variable. > > So . . . I want to be able to skip a number of lines at the beginning of > the input file. It seemed like IO#lineno= would be the obvious solution: > > in_fh = File.open(infile, 'r') > out_fh = File.open(outfile, 'w') > > in_fh.lineno = 1 > > in_fh.each_line do |l| > out_fh << l > end > > Unfortunately, that doesn't give me what I expected at all. In fact, > what I end up with is an empty file. Am I misunderstanding what > IO#lineno= does? Is there something about the way IO#each_line works > that is interacting badly with an incremented line number? What do I > need to do differently to make this work? > The way I read the ri doc for lineno=, it appears that all it does is determine the value that lineno returns the next time you call it. That is, it doesn't move the read position in the file. I think what you're looking for is IO#seek, but notice that it seek doesn't operate on lines, only on byte offsets. -- RMagick: http://rmagick.rubyforge.org/