文件中的文本打印不正确

时间:2014-06-18 08:11:01

标签: ruby learn-ruby-the-hard-way

解决这个问题并且我已经完全按照问题状态键入了代码 - 甚至尝试复制和粘贴以查看它是否是我做错了但不是。

我所拥有的代码位于本文的底部。我发送的参数'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)

1 个答案:

答案 0 :(得分:0)

修改 看起来您使用的测试文件仅包含字符\r以指示换行符,而不是窗口\r\n或linux \n。您的文本编辑器可能会将\r解释为换行符,但ruby不会。

原始答案:

关于print_all的第一个问题,我无法重现它。你如何运行脚本?

在第二个问题中,您使用的方法是file.readlines()(请注意最终的 s ),而不是file.readline()

file.readlines()读取整个文件并将其内容返回到数组中,每行作为数组的元素。 这就是您在第一次通话中获取整个文件的原因。后续调用返回空数组,因为你是文件的结尾(你需要"倒带"正如你之前继续读取文件一样)。

file.readline()读取文件的一行并将其内容作为字符串返回,这可能是您想要的。

我链接到ruby文档,以便进一步阅读(没有双关语意)关于这个问题。请注意,相关方法在IO类的文档中有详细说明,因为File继承自此类,readlines / readline方法继承自IO