解决了这个问题,我已经完全像问题状态一样输入了代码 - 甚至尝试复制和粘贴以查看它是否是我做错的事情,但事实并非如此。
我拥有的代码在这篇文章的底部。我正在发送参数“test.txt”,其中包含:
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here
但是,当我运行代码时,在 print_all(current_file) 期间,它只会打印“在这里有很多很多乐趣”。- 这是文件的最后一行。
在它应该打印出每一行的地方,它打印:
1 ["This is stuff I typed into a file. \rIt is really cool stuff. \rLots and lots of fun to have in here.\r\r"]
2 []
3 []'
基本上将所有行捕获为 1 行,并且在应该打印第 2 行和第 3 行的地方不打印任何内容。
有任何想法吗?
input_file = ARGV[0]
def print_all(f)
puts f.read()
end
def rewind(f)
f.seek(0, IO::SEEK_SET)
end
def print_a_line(line_count, f)
puts "#{line_count} #{f.readlines()}"
end
current_file = File.open(input_file)
puts "First let's print the whole file:"
puts # a blank line
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 += 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)