【发布时间】:2017-04-22 21:16:03
【问题描述】:
我正在完成 Learn 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 "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”,并且在此参数上调用gets.chomp 方法。这是代码运行时出现在控制台上的内容(使用示例文本文件作为 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”而不使用任何附加方法不会打印文本文件中的行?谢谢!
【问题讨论】:
标签: ruby methods file-io user-input