From: Relm Date: 2004-06-08T18:08:41+09:00 Subject: Re: Newbie wondering about command line arguments On Tue, 8 Jun 2004, Paul Emmons wrote: > I have read that unless somehow told otherwise, a Ruby program uses > the command-line arguments as input file names and reads them one > after the other as though they came from STDIN. If I have used the > last argument as an output file name, why doesn't it run into trouble > when it comes to this argument and tries to use it as in input file? If you are only testing with small input files, then the last input file may well be empty when you try to read from it. > #!/usr/bin/env ruby > # Reverses characters in every line of a file > > if STDIN.tty? > puts "No. of args = #{ARGV.size}" > ARGV.each { |a| puts "Arg = #{a}" } > if ARGV.size>1 > $stdout=File.new(ARGV[ARGV.size-1], "w") This truncates the last file to zero bytes. > end > end > > while line = gets > line.chomp! > puts line.reverse This puts a reversed line into a buffer. It does not write anything to the last file until the buffer is full. > end So, for small input files, everything goes into a buffer. When you try to read a line from the last file, there are no lines; the loop ends, the buffer flushes, and all is well. For larger input files, the buffer gets flushed earlier, so there are actual lines to read from the last file. Those lines get read, then written to the end of the file, where they are read again, and written again, and read, and written... As Joel suggested: ARGV.pop -- Relm