adamscott adamscott - 7 months ago 6
Ruby Question

Printing out one line of a file in a Ruby script

I am going through "Learn Ruby the Hard Way" and I came across the method

print_a_line
in exercise 20.

input_file = ARGV.first
current_file = open(input_file)

def print_a_line(line_count, f)
puts "#{line_count}, #{f.gets.chomp}"
end

current_line = 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)


This method is about to take the current line count and output to the terminal only the contents of the file from that line. I don't understand how the method knows to print the line of the file that is associated with
current_line
. When I look at this I would think
#{f.gets.chomp)
would return the entire contents of they file. How does the method know to look at the
current_line
and print out the associated line of the file?

Answer

The gets method being called in print_a_line reads a single line from the file (not the entire contents). The File object referenced by current_file keeps track of the current position within the file, so each time gets is called, the next line is returned.

Nothing is looking at current_line to determine which line to read.