'gets'方法说明:在没有任何用户输入的情况下打印字符串?



我正在通过学习红宝石进行艰难的练习,并在练习20

中对语法有疑问
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)

在" print_a_line"函数中,如果字符串交换为字符串,则参数" f"在此参数上被调用。这是运行代码时在控制台上出现的内容(使用示例文本文件作为argv.first,带有三行)

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

我的问题是:我们为什么要在" F"参数上调用gets.chomp?"获取"用户输入来自哪里?为什么可以使用此功能,而是使用" F"而没有任何附件的方法不打印文本文件中的行?谢谢!

gets实际上没有用户输入的。在这种情况下,您既不习惯:

puts "what's your answer?"
answer = gets.chomp

通常,这是io对象上的一种方法,它读取字符串("字符串"定义为"当前位置的所有字符,直到(并包括)折线")。

在您的示例中,它是在File对象上调用的(因此,从打开的文件中读取内容,按行逐行读取)。"裸"表单读取文件中的行,通过命令行参数传递,或(如果没有传递文件)从标准输入中传递。请注意,标准输入不一定是从键盘读取的(这就是您所说的"用户输入")。输入数据可以将其输送到您的程序中。

,但仅使用" f"而没有任何附加的方法不会打印文本文件中的行

f是对文件对象的引用。它不代表任何有用的可打印内容。但是您可以使用它来读取文件中的一些内容(f.gets)。

gets您看到的不是用户输入。相反,它属于IO类,并阅读IO流的下一行。您可以在Ruby Doc中找到这个https://ruby-doc.org/core-2.3.0/io.html#method-i-gets

文件中的每一行都以newline字符("n")结尾,方法puts显示字符串和newline,因此它将显示字符串和两个新行。CHOMP方法将删除字符串末端的新线路,因此将仅显示一个新线。

请参阅doc => https://ruby-doc.org/core-2.2.0/string.html#method-i-chomp

相关内容

最新更新