How to Read a file in Ruby

In ruby you read a file in two steps. First open the file, and then iterate over the contents. (In this instance we loop over the contents of a text file so the built-in each_line is what we want.)

We read the file in a ruby block. This way the File.open call automatically closes the file when the block finishes.

File.open("read.rb", "r") do |f|
  f.each_line do |line|
    puts line
  end
end

Related Posts