Ruby 控制台在打印文件中的行时覆盖行
我开始学习 Ruby 时遇到了一个恼人的问题。我已将一个文本文件导入到我的程序中,我想迭代其中的行并将它们打印到屏幕上。
当我这样做时,控制台会覆盖最后打印的行并将新的行写在顶部。为什么会发生这种情况以及如何解决?
这是我的代码:
passwords = File.open('C:\Users\Ryan\Desktop\pw.txt', 'r')
lines = passwords.gets
for line in lines
puts line
end
更新: 循环的行为非常奇怪。我在其中放入了一个睡眠语句,它所做的只是睡眠一次,然后继续输出行。我本以为它会在输出每一行之前休眠。示例如下:
passwords.each do |line|
sleep 1
puts line.chomp
end
更新 2: 我刚刚创建了一个新的文本文件,并在其中输入了一些随机内容进行测试,它工作正常。看起来原始文件有一些错误的字符/编码,导致控制台的打印混乱。
I have started learning Ruby and I have come across an annoying problem. I have imported a text file into my program and I want to iterate over the lines in it and print them out to the screen.
When I do this, the console overwrites the last printed out line and writes the new one on top. Why is this happening and how can I solve it?
Here is my code:
passwords = File.open('C:\Users\Ryan\Desktop\pw.txt', 'r')
lines = passwords.gets
for line in lines
puts line
end
Update:
The loop is acting very strange. I put a sleep statement into it and all it did was sleep once then continue to output the lines. I would have expected it to sleep before outputting each line. Example below:
passwords.each do |line|
sleep 1
puts line.chomp
end
Update 2:
I just created a new text file and typed some random stuff into it for testing and it works fine. Looks like the original file had some bad characters/encoding which messed up the printing to the console.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否遇到 EOL(又称为行尾)问题?试试这个:
chomp
调用将剥离关闭任何\n
、\r
或\r\n
行结尾,然后puts
将附加本机停产。Do you have an EOL (AKA end-of-line) problem? Try this:
The
chomp
call will strip off any\n
,\r
, or\r\n
line endings, thenputs
will append the native EOL.或者
or
最后我发现文本文件是我的问题的原因。我创建了一个具有相同内容的新项目,它开始按照我的预期工作。
In the end I found out that the text file was the cause of my problem. I created a new one with the same content and it started working how I intended.