draw draw - 1 year ago 139
Ruby Question

How to read lines of a file in Ruby

I was trying to use the following code to read lines from a file. But when reading a file, the contents are all in one line:

File.open('xxx.txt').each do |line|
print "#{line_num += 1} #{line}"

But this file prints each line separately.

I have to use stdin, like
ruby my_prog.rb < file.txt
, where I can't assume what the line-ending character is that the file uses. How can I handle it?

Answer Source

I believe my answer covers your new concerns about handling any type of line endings since both "\r\n" and "\r" are converted to Linux standard "\n" before parsing the lines.

To support the "\r" EOL character along with the regular "\n", and "\r\n" from Windows, here's what I would do:

text.gsub!(/\r\n?/, "\n")
text.each_line do |line|
  print "#{line_num += 1} #{line}"

Of course this could be a bad idea on very large files since it means loading the whole file into memory.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download