gets.chomp在ruby中的函数内部

Sea*_*rko 4 ruby function learn-ruby-the-hard-way

我正在经历"以艰难的方式学习Ruby",而在练习20中,有一段我不理解的代码片段.我不明白为什么在函数"print_a_line"中调用f的gets.chomp.

input_file = ARGV.first

def print_all(f)
  puts f.read
end

def rewind(f)
  f.seek(0)
end

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

current_file = open(input_file)

puts "First let's print the whole file:\n"

print_all(current_file)

puts "Now let's rewind, kind of like a tape."

rewind(current_file)

puts "Let's print three lines:"

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)
Run Code Online (Sandbox Code Playgroud)

因此,我不明白输出的第二部分是如何产生的.我理解它是传递给代码的test.txt文件的前3行,但我不明白f.gets.chomp是如何产生这一行的.

$ ruby ex20.rb test.txt
First let's print the whole file:
This is line 1
This is line 2
This is line 3
Now let's rewind, kind of like a tape.
Let's print three lines:
1, This is line 1
2, This is line 2
3, This is line 3
Run Code Online (Sandbox Code Playgroud)

til*_*use 7

File对象f保持跟踪(以及它引用的东西跟踪)它在文件中读取的位置.您可以将其视为在文件中读取时前进的光标.当你告诉fgets,它读取,直到达到新的生产线.它们的关键在于f记住你所处的位置,因为读数会提升"光标".该chomp电话根本不会进入这一部分.因此,每次调用f.gets只读取文件的下一行并将其作为字符串返回.

chomp只操作由返回的字符串f.gets,其文件对象没有任何影响.

编辑:要完成答案:chomp返回删除尾部换行符的字符串.(从技术上讲,它删除了记录分隔符,但这几乎与新行不同.)这来自Perl(AFAIK),其想法是,基本上你不必担心你的特定输入形式是否通过了你是否换行符.