简体   繁体   中英

Ruby console overwrites line when printing out lines in a file

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.

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.

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 }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM