简体   繁体   中英

Ruby read file line issue

I'm trying to read a file into a string. For instance, I tried reading this file:

123456  
23456  
3456  
456  
56  
6

I tried:

contents = File.open("test.txt", "rb").read  
print contents

IO.foreach('test.txt') do |line|  
  print line  
end

File.open('test.txt', 'r').each_line do |line|
  print line
end     

but I seem to get a single line that will overwrite it's contents with each new line. I get 666666 .

The issue has to be the fact that the file is using the CR line terminator (or your terminal is messed up and not responding to LF). print does not go into the new line by default (you should use puts if that's what you want), and each_line does not strip the line terminator. So what happens is, print "123456\\r " prints out 123456 and then returns the cursor to the start of the line, without moving to the next line (so the cursor is on 1 . Then when you print "23456\\r" , it will overwrite the first five characters and again come back to the start, the current state being 234566 ... In the end, 566666 will get overwritten by "6\\r" for the final 666666 .

Why not try the simple solution

# ruby sample code.
# process every line in a text file with ruby (version 1).
file='test.txt'
File.readlines(file).each do |line|
  puts line
end

Second approach

# ruby sample code.
# process every line in a text file with ruby (version 2).
file='test.txt'
f = File.open(file, "r")
f.each_line { |line|
  puts line
}
f.close

Answer Source

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