When Ruby's IO class opens a file, it sets the $.
global variable to 0. For each line that is read that variable is incremented. So, to know what line has been read simply use $.
.
Look in the English module for $.
or $INPUT_LINE_NUMBER
.
We can also use the lineno
method that is part of the IO class. I find that a bit more convoluted because we need an IO stream object to tack that onto, while $.
will work always.
I'd write the loop more simply:
File.foreach(ARGV[0]) do |line|
Something to think about is, if you're on a *nix system, you can use the OS's built-in grep
or fgrep
tool to greatly speed up your processing. The "grep" family of applications are highly optimized for doing what you want, and can find all occurrences, only the first, can use regular expressions or fixed strings, and can easily be called using Ruby's %x
or backtick operators.
puts `grep -inm1 abacus /usr/share/dict/words`
Which outputs:
34:abacus
-inm1
means "ignore character-case", "output line numbers", "stop after the first occurrence"