Karl von Laudermann
8/25/2006 5:46:00 PM
Oliver Bandel wrote:
>
> ====================================
> def look_for_begin
> while line = gets
> if line =~ /^begin/
> puts line
> # return
> end
> end
> end
>
> ARGF.each { look_for_begin }
> ====================================
The problem is that you've got two loops here. ARGF.each calls
look_for_begin once for each line of each file passed in. Then within
look_for_begin, it has another loop that runs until there are no more
lines to process. So what happens is this: without the return
statement, the look_for_begin function is called once, and its while
loop runs through all of the lines until until there are no more to
process. The function is not called again, because the ARGF.each loop
terminates immediately, because all lines have been read.
If you put in the return, the while loop runs until it finds the first
"begin". Then the function returns. Then the ARGF.each loop calls
look_for_begin again, and it picks up where it left off, processing the
line after the one where "begin" was found.
So, either way, your function process every line of every file. The
only difference you cause by adding and removing the return statement
is whether it processes all of the lines in one call to look_for_begin,
or over multiple calls.
I think what you wanted to do is use ARGV.each instead of ARGF.each, to
iterate over the list of file names, and pass each file name into the
look_for_begin function. Within the function, you'd process only the
lines in that file. In other words, like this:
def look_for_begin(fn)
IO.foreach(fn) do |line|
if line =~ /^begin/
puts line
return
end
end
end
ARGV.each {|fn| look_for_begin(fn) }