Ruby 控制台在打印文件中的行时覆盖行

发布于 2024-11-01 05:58:46 字数 532 浏览 4 评论 0原文

我开始学习 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北城孤痞 2024-11-08 05:58:46

您是否遇到 EOL(又称为行尾)问题?试试这个:

passwords = File.open('C:\Users\Ryan\Desktop\pw.txt', 'r')
lines = passwords.gets
lines.each { |line| puts line.chomp }
passwords.close

chomp 调用将剥离关闭任何 \n\r\r\n 行结尾,然后 puts 将附加本机停产。

Do you have an EOL (AKA end-of-line) problem? Try this:

passwords = File.open('C:\Users\Ryan\Desktop\pw.txt', 'r')
lines = passwords.gets
lines.each { |line| puts line.chomp }
passwords.close

The chomp call will strip off any \n, \r, or \r\n line endings, then puts will append the native EOL.

暖阳 2024-11-08 05:58:46
File.open('C:\Users\Ryan\Desktop\pw.txt') do |line|
  while not line.eof?
    puts line.readline.chomp
  end
end

或者

File.read("file").each { |line| puts line.chomp }
File.open('C:\Users\Ryan\Desktop\pw.txt') do |line|
  while not line.eof?
    puts line.readline.chomp
  end
end

or

File.read("file").each { |line| puts line.chomp }
浮云落日 2024-11-08 05:58:46

最后我发现文本文件是我的问题的原因。我创建了一个具有相同内容的新项目,它开始按照我的预期工作。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文