On 12/3/07, Johnathan S. [email protected] wrote:
I’ve changed my approach as i dont actually want to count the lines
so i now have this:
ARGV.each do |fn|
(fn == ‘reference.txt’ ? STDIN : File.open(fn)).each_line do |l|
ARGV.each will iterate through every parameter you pass. Since your
script is so simple, you’re better of with ARGV. You’d have to
check the length and see if ARGV.length == 1.
A more Ruby-like approach is this:
#!/usr/bin/env ruby -wKU
if ARGV.length != 1
puts “Syntax is: ruby readfile.rb filename”
File.open(ARGV, “r”) do |file|
while line = file.gets
Using File.open with a block will automatically open and close the
file handler and that’s a pretty decent practice to start with.
I’d highly recommend you the PickAxe book (Programming Ruby, 2nd
edition). It does a great job explaining Ruby concepts (the code above
is just a rip-off from Mr. Thomas’s example on page 129). However,
I’ve heard people complaining that it’s a bit daunting for new
programmers. Maybe you’d feel a bit better with Learning to Program by
Chris P. if words like “iterators” and “inheritance” make you sweat.