Ruby 解释';获取';方法:在没有任何用户输入的情况下打印字符串?
我正在进行学习Ruby the Hard Way的练习,在练习20中有一个关于语法的问题Ruby 解释';获取';方法:在没有任何用户输入的情况下打印字符串?,ruby,methods,file-io,user-input,Ruby,Methods,File Io,User Input,我正在进行学习Ruby the Hard Way的练习,在练习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
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”if string插值,并对该参数调用get.chomp方法。这是运行代码时控制台上显示的内容(使用示例文本文件ARGV.first,共三行)
我的问题是:为什么我们要在“f”参数上调用get.chomp?“获取”用户输入来自哪里?为什么这样做,但是使用“f”而不使用任何附加方法的justing不会打印文本文件中的行?谢谢 文件中的每一行都以一个换行符(
“\n”
)结尾,方法put
显示字符串和一个换行符,以便显示字符串和两个新行。chomp方法将删除字符串末尾的新行,因此只显示一个新行
查看doc=>您看到的
获取的不是供用户输入的。相反,它属于IO类并读取IO流的下一行。
你可以在Ruby文档中找到这个
获取
实际上与用户输入无关。无论是在这种情况下,还是在“通常”的形式下,您都不可能习惯于:
puts "what's your answer?"
answer = gets.chomp
通常,它是IO对象上读取字符串的方法(“字符串”定义为“从当前位置到(包括)换行符的所有字符”)
在您的示例中,它在文件
对象上被调用(因此,逐行从打开的文件中读取内容)。从文件中读取行,通过命令行参数传递,或者(如果未传递任何文件)从。请注意,标准输入不一定是从键盘读取的(这就是所谓的“用户输入”)。可以将输入数据输入到程序中
但是仅仅使用“f”而不使用任何附加方法不会打印文本文件中的行
f
是对文件对象的引用。它不表示任何有用的可打印内容。但是您可以使用它从文件中读取一些内容,您可以这样做(f.gets
)。ok,删除错误链接。回答得很好,也澄清了我的困惑。@SergioTulentsev刚刚做了-仍然习惯于这些堆栈溢出过程…再次感谢!谢谢感谢您的反馈
puts "what's your answer?"
answer = gets.chomp