When the Ruby IO class opens a file, it sets the global variable $. equal to 0. For each row that is read, this variable is incremented. So, to find out which line was read, just use $. .
Check out the English module $. or $INPUT_LINE_NUMBER .
We can also use the lineno method, which is part of the IO class. I find this a bit more confusing because we need an input / output stream object to bind it, while $. will always work.
I would write a loop more simply:
File.foreach(ARGV[0]) do |line|
Something to think about if you are on a * nix system, you can use the built-in grep or fgrep to speed up processing. The grep family of applications is highly optimized to do what you want and can find all occurrences, only the first can use regular expressions or fixed strings and can be easily called using Ruby %x or backtick statements.
puts `grep -inm1 abacus /usr/share/dict/words`
What outputs:
34:abacus
-inm1 means "ignore case of characters", "line numbers of output", "stop after first occurrence"
source share