【发布时间】:2017-05-02 06:34:57
【问题描述】:
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 "Let's rewind kind a like a tape"
rewind(current_file)
puts "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
我确信有一个与此类似的帖子,但我的问题有点不同。如上所示,print_a_line 方法有两个参数 line_count 和 f。
1) 据我了解, line_count 参数仅用作 current_line 变量,它只是一个整数。它与 rewind(f) 方法有什么关系,因为当我运行代码时,方法 print_a_line 显示如下:
1, Hi
2, I'm a noob
其中 1 是第一行,2 是第二行。 line_count 只是一个数字,ruby 怎么知道 1 是第 1 行,2 是第 2 行?
2) 为什么在方法 print_a_line 中使用gets.chomp?如果我像这样通过 f
def print_a_line(line_count, f)
puts "#{line_count}, #{f}"
end
我会得到一个疯狂的结果
1, #<File:0x007fccef84c4c0>
2, #<File:0x007fccef84c4c0>
【问题讨论】: