274

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:

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

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?

6

8 Answers 8

601

Ruby does have a method for this:

File.readlines('foo', chomp: true).each do |line|
    puts(line)
end

http://ruby-doc.org/core-1.9.3/IO.html#method-c-readlines

6
  • this methond slower than methond that's @Olivier L.
    – HelloWorld
    Jan 12, 2013 at 2:33
  • 1
    @HelloWorld Probably because it's deleting each preceding line from memory and loading in each line into memory. May be wrong, but Ruby's probably doing things properly (so that large files don't cause your script to crash).
    – Starkers
    Sep 27, 2013 at 11:19
  • Can you use with_index with this as well? Jul 5, 2015 at 18:11
  • 3
    Yes, you can, e.g. File.readlines(filename).each_with_index { |line, i| puts "#{i}: #{line}" }
    – wulftone
    Jun 17, 2017 at 18:24
  • 1
    This method seems better. I am reading very large files and this way it doesn't crash the application by attempting to load the entire file into memory at once.
    – Shelby S
    Aug 31, 2017 at 15:10
440
File.foreach(filename).with_index do |line, line_num|
   puts "#{line_num}: #{line}"
end

This will execute the given block for each line in the file without slurping the entire file into memory. See: IO::foreach.

5
  • 15
    This is the answer - idiomatic Ruby and doesn't slurp the file. See also stackoverflow.com/a/5546681/165673
    – Yarin
    Feb 22, 2015 at 22:27
  • 5
    All hail the Ruby gods! Jul 2, 2015 at 15:26
  • how to go to second line inside the loop ? Nov 20, 2017 at 7:56
  • You must use 'filename' instead of filename. Also use line_num+1 instead of line_num so first line begins in 1 and not in 0.
    – Smeterlink
    Jul 5, 2021 at 0:03
  • 2
    @Smeterlink filename is a variable containing a string such as 'xxx.txt'.
    – nekketsuuu
    Jul 27, 2021 at 10:55
152

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:

line_num=0
text=File.open('xxx.txt').read
text.gsub!(/\r\n?/, "\n")
text.each_line do |line|
  print "#{line_num += 1} #{line}"
end

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

7
  • That regex didn't work for me. Unix format uses \n, windows \r\n, mac uses \n -- .gsub(/(\r|\n)+/,"\n") worked for me with all cases.
    – Pod
    May 2, 2013 at 8:36
  • 5
    Correct regex should be /\r?\n/ which will cover both \r\n and \n without combining empty lines as Pod's comment would do May 23, 2013 at 17:05
  • 15
    This will read the entire file into memory, which could be impossible depending on how large the file is.
    – eremzeit
    Jun 25, 2013 at 2:38
  • 1
    This method is very highly inefficient, talabes answer here stackoverflow.com/a/17415655/228589 is the best answer. Please verify the implementation these two methods. Jan 6, 2014 at 17:52
  • 1
    This is not the ruby way. The answer below shows the right behavior.
    – Merovex
    Dec 26, 2015 at 19:53
19

Your first file has Mac Classic line endings (that’s "\r" instead of the usual "\n"). Open it with

File.open('foo').each(sep="\r") do |line|

to specify the line endings.

3
  • 1
    Sadly, there’s nothing like the universal newlines in Python, at least that I know of.
    – Josh Lee
    May 16, 2011 at 3:40
  • one more question, I have to use stdin, like ruby my_prog.rb < file.txt, where I can't assume what the line ending char the file uses... How can I handle it?
    – draw
    May 16, 2011 at 3:49
  • Olivier’s answer seems helpful, if you’re OK with loading the whole file into memory. Detecting newlines while still scanning the file will take a bit more work.
    – Josh Lee
    May 16, 2011 at 23:27
9

I'm partial to the following approach for files that have headers:

File.open(file, "r") do |fh|
    header = fh.readline
    # Process the header
    while(line = fh.gets) != nil
        #do stuff
    end
end

This allows you to process a header line (or lines) differently than the content lines.

7

It is because of the endlines in each lines. Use the chomp method in ruby to delete the endline '\n' or 'r' at the end.

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

how about gets ?

myFile=File.open("paths_to_file","r")
while(line=myFile.gets)
 //do stuff with line
end
4

Don't forget that if you are concerned about reading in a file that might have huge lines that could swamp your RAM during runtime, you can always read the file piece-meal. See "Why slurping a file is bad".

File.open('file_path', 'rb') do |io|
  while chunk = io.read(16 * 1024) do
    something_with_the chunk
    # like stream it across a network
    # or write it to another file:
    # other_io.write chunk
  end
end

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.