简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM