Use File.foreach: File.foreach("notes.txt", chomp: true) { |line| puts line } reads one line at a time, drops the line ending, and closes the file when the loop ends. It never holds the whole file in memory. For a small file you want as an array, use File.readlines("notes.txt", chomp: true); for one string, use File.read("notes.txt").
Ruby has several ways to read a file, and they differ in one thing that matters: whether the whole file is loaded into memory at once. File.foreach and each_line stream line by line; File.read and File.readlines load everything. There is no with open(...) block to remember as in Python: the block forms close the file for you. The sections below cover File.foreach, reading a whole file, File.open with each_line and gets, line endings and chomp, binary files with File.binread, and files that may not exist, then a table to pick from. Every example writes its own sample file first, then reads it. Each example runs on this page: hit Run, then edit the code and run it again.
1File.foreach: one line at a timeRecommended
File.foreach(path) opens the file, yields each line to the block, and closes the file when the block finishes or raises. Only the current line is in memory, so it works the same on a 1 KB file and a 10 GB log. Each line keeps its "\n"; pass chomp: true to drop it. Without a block, foreach returns an Enumerator, so every Enumerable method works on the lines: with_index(1) for line numbers, first(n) or find to stop early, count to count lines, and lazy to filter without building arrays.
File.write("notes.txt", "buy milk\ncall Sam\nfix the bike\n") # Each line still ends with "\n" File.foreach("notes.txt") { |line| p line } # chomp: true drops the line ending File.foreach("notes.txt", chomp: true) do |line| puts "- #{line}" end # Line numbers from 1 File.foreach("notes.txt", chomp: true).with_index(1) do |line, n| puts "#{n}: #{line}" end # Without a block you get an Enumerator lines = File.foreach("notes.txt", chomp: true) p lines.class p lines.first(2) p lines.count p lines.find { |line| line.start_with?("call") } p lines.lazy.select { |line| line.include?("i") }.first(1)
Output
The first loop shows the raw lines, "buy milk\n" and so on; with chomp: true they come back as "buy milk". with_index(1) numbers them from 1 instead of 0. first(2), find and the lazy chain stop reading as soon as they have their answer and close the file, which matters on a large file: find returns "call Sam" after two lines, and the lazy filter stops at the first line with an i. Each call on the Enumerator opens the file again, so count reads it from the start and prints 3.
2The whole file: File.read and File.readlines
When the file is small (a config, a word list, test data), loading it in one call is simpler. File.read returns the whole file as one string. File.readlines returns an array with one string per line and takes the same chomp: true option. IO.readlines and IO.read, common in older answers, are the same methods (File inherits them from IO). If you already have the text in a string, lines splits it the same way. Both methods hold the whole file in memory, so prefer File.foreach for files that can grow.
File.write("notes.txt", "buy milk\ncall Sam\nfix the bike\n") # One string text = File.read("notes.txt") p text # An array of lines, with and without the "\n" p File.readlines("notes.txt") lines = File.readlines("notes.txt", chomp: true) p lines puts "#{lines.size} lines, the last two: #{lines.last(2)}" # IO.readlines is the same method p IO.readlines("notes.txt", chomp: true) == lines # Splitting a string you already have p text.lines(chomp: true) p text.split("\n")
Output
File.read gives back the file exactly, newlines included: "buy milk\ncall Sam\nfix the bike\n". File.readlines without options keeps the "\n" on every element, which is why most code passes chomp: true. With the array in hand, lines.last(2) gives the last lines and lines.size the count. text.lines(chomp: true) and text.split("\n") agree here, but they differ on Windows line endings, as section 4 shows.
3File.open with each_line or a gets loop
File.foreach is a shortcut for opening the file and calling each_line on it. Open the file yourself with File.open(path) { |f| … } when you need the file object: to read a header line first with gets, to ask for the current line number with lineno, or to mix line reads with other reads. gets returns the next line, or nil at the end of the file, which is what makes the classic while (line = f.gets) loop stop. The block form closes the file when the block ends; without a block, you must call close yourself.
File.write("scores.csv", "name,score\nAnn,91\nBob,78\nCy,85\n") File.open("scores.csv") do |f| header = f.gets(chomp: true) p header.split(",") f.each_line(chomp: true) do |line| name, score = line.split(",") puts "line #{f.lineno}: #{name} scored #{score}" end end # A gets loop: gets returns nil at the end of the file File.open("scores.csv") do |f| while (line = f.gets) print line if line.include?("B") end end # Without a block, close the file yourself f = File.open("scores.csv") p f.readline f.close p f.closed?
Output
gets consumes the header, so each_line starts at the second line and lineno reports line 2 for Ann. The gets loop prints Bob,78 with print because the line still has its newline. readline is gets that raises EOFError at the end of the file instead of returning nil. A bare while (line = gets), with no file object, reads the files named on the command line or, if there are none, standard input; this page passes no arguments and no input, so there it returns nil at once. For real CSV with quoted fields, use the csv library instead of split(",").
4Line endings: chomp, \r\n and blank lines
Files saved on Windows end each line with "\r\n", and the last line of any file may have no newline at all. chomp (and the chomp: true option) handles both: it removes one trailing "\n", "\r\n" or "\r", and leaves a line without one alone. split("\n") leaves the "\r" behind, and chop removes the last character whatever it is, so both cause bugs on such files. strip also works but removes leading and trailing spaces too.
# Windows line endings, no newline after the last line File.write("windows.txt", "one\r\ntwo\r\nthree") File.foreach("windows.txt") { |line| p line } # chomp removes "\n", "\r\n" or "\r" p File.readlines("windows.txt", chomp: true) p File.read("windows.txt").lines(chomp: true) # split("\n") leaves the "\r" behind p File.read("windows.txt").split("\n") # chomp vs strip vs chop p " two \r\n".chomp p " two \r\n".strip p "three".chop # Blank lines come back as empty strings File.write("blank.txt", "a\n\nb\n\n") lines = File.readlines("blank.txt", chomp: true) p lines p lines.reject(&:empty?)
Output
The raw lines are "one\r\n", "two\r\n" and "three" with no newline, and chomp: true turns all three into clean words. split("\n") returns "one\r", a string that prints like one but fails == against it. chomp keeps the inner spaces of " two " while strip removes them, and "three".chop gives "thre", the bug you get when the last line has no newline. Blank lines stay in the array as ""; reject(&:empty?) removes them.
5Binary files: File.binread
For images, archives or any data that is not text, read with File.binread (or File.open(path, "rb")). It returns a string tagged with the BINARY encoding (also called ASCII-8BIT), where every byte is one character, and it never converts line endings. File.read returns the same bytes on Linux and macOS but tags them as UTF-8, which makes size, slicing and regexes treat them as text. bytes gives the values as integers and unpack decodes fixed-size fields.
# Write 8 raw bytes, some of them not valid text File.binwrite("header.bin", [67, 66, 1, 0, 13, 10, 0, 255].pack("C*")) data = File.binread("header.bin") p data p data.encoding p data.bytesize p data.bytes # Only the first 4 bytes p File.binread("header.bin", 4) # Decode: 2 characters, then a 16-bit little-endian integer p data.unpack("a2 v") p data.unpack1("H*") # File.read returns the same bytes tagged as UTF-8 text = File.read("header.bin") p text.encoding p text.valid_encoding?
Output
The binary string prints its unprintable bytes as escapes, such as \x01 and \xFF, and its encoding shows as #<Encoding:BINARY (ASCII-8BIT)>: BINARY and ASCII-8BIT are two names for the same encoding. bytes gives [67, 66, 1, 0, 13, 10, 0, 255], unpack("a2 v") reads "CB" and the integer 1, and unpack1("H*") is a hex dump. The same file read with File.read is tagged UTF-8 and valid_encoding? says false, because byte 255 is not UTF-8. On Windows, text mode also turns "\r\n" into "\n", which corrupts binary data; binread avoids that everywhere.
6Files that may not exist
File.exist?(path) is true for any existing path, directories included; File.file? is true only for regular files and File.directory? only for directories. Checking first and reading second has a gap: the file can disappear or be unreadable between the two calls. The sturdier pattern is to read and rescue the error. A missing file raises Errno::ENOENT, a subclass of SystemCallError, which also covers other operating-system errors such as Errno::EACCES (permission denied) and Errno::EISDIR (the path is a directory).
File.write("notes.txt", "buy milk\n") Dir.mkdir("logs") p File.exist?("notes.txt") p File.exist?("missing.txt") p File.exist?("logs") p File.file?("logs") p File.directory?("logs") # Read first, rescue the error def read_lines(path) File.readlines(path, chomp: true) rescue Errno::ENOENT => e puts "skipped: #{e.message}" [] end p read_lines("notes.txt") p read_lines("missing.txt") # SystemCallError catches every Errno:: error begin File.foreach("logs") { |line| puts line } rescue SystemCallError => e p e.class end
Output
File.exist?("logs") is true but File.file?("logs") is false, so use file? when you are about to read. The missing file prints No such file or directory @ rb_sysopen - missing.txt and read_lines returns [] instead of crashing. Left unrescued, the same call stops the script with No such file or directory @ rb_sysopen - missing.txt (Errno::ENOENT) on standard error. Reading the directory raises Errno::EISDIR, which the broader SystemCallError catches.
7Which should you use?
| Method | Returns | Memory | Best for |
|---|---|---|---|
| File.foreach(path, chomp: true) | One line per block call | One line at a time | Most line-by-line work, any file size |
| File.readlines(path, chomp: true) | Array of lines | Whole file | Small files you index, sort or reuse |
| File.read(path) | One string | Whole file | Parsing the whole text (JSON, YAML, regex) |
| File.open { |f| f.each_line } | Lines plus the file object | One line at a time | Header lines, lineno, mixed reads |
| File.binread(path) | BINARY string | Whole file | Images, archives, raw bytes |
| rescue Errno::ENOENT | Your fallback | n/a | Files that may be missing (sturdier than File.exist?) |
Frequently asked questions
How do I read the last N lines of a file in Ruby?
For a small file, File.readlines(path, chomp: true).last(3). For a large one, stream it and keep only the last N in a buffer: File.foreach(path, chomp: true).each_with_object([]) { |line, buf| buf << line; buf.shift if buf.size > 3 }. On a 10-line file both return ["line 8", "line 9", "line 10"].
How do I count the lines in a file?
File.foreach(path).count streams the file and counts every line, including a last line with no newline. File.read(path).count("\n") counts newline characters instead, so it is one short when the file does not end with a newline: on a 10-line file without a final newline, the first gives 10 and the second 9.
Why does File.exists? not work?
It was a deprecated alias and has been removed; current Ruby raises undefined method 'exists?' for class File. Use File.exist? (no s), or File.file? when you also need it to be a regular file.
What is the difference between IO.readlines and File.readlines?
None for files: File is a subclass of IO, so File.readlines, File.read and File.foreach are the IO methods. Older Rubies treated a path starting with | as a shell command in the IO forms; here IO.readlines("|echo hi") just looks for a file of that name and raises No such file or directory @ rb_sysopen - |echo hi. Calling them on File reads plainly everywhere, which makes File the safer spelling.
How does while line = gets work in Ruby?
A bare gets reads from ARGF: the files named on the command line one after another, or standard input when there are none. It returns nil at the end, which ends the loop. Use f.gets on an opened file to read that file only. On this page there are no arguments and no input, so gets returns nil straight away.
How do I read a large file without loading it into memory?
Use File.foreach or File.open(path) { |f| f.each_line { … } }, which hold one line at a time, and avoid File.read and File.readlines, which load the whole file. To stop early, call first(n) or find on File.foreach(path). For binary data, read fixed-size chunks with f.read(65536) in a loop until it returns nil.