Introduction

The following code reads and outputs text in a file.

Demo

File.open("main.rb").each { |line| puts line }

Result

The File class's open method is used to open the text file, text.txt.

Via the File object, the each method returns each line one by one.

You can also do it this way:

Demo

File.new("main.rb", "r").each { |line| puts line }

Result

By opening a file, you're creating a new File object that you can then use.

The second parameter, "r", defines that you're opening the file for reading.

This is the default mode.

Open vs new

File.open can accept a code block, and once the block is finished, the file will be closed automatically.

File.new returns a File object referring to the file.

To close the file, you have to use its close method.

First, look at File.open:

Demo

File.open("main.rb") do |f| 
  puts f.gets 
end

This code opens text.txt and then passes the file handle into the code block as f.

puts f.gets takes a line of data from the file and prints it to the screen.

Now, have a look at the File.new approach:

Demo

f = File.new("main.rb", "r") 
puts f.gets 
f.close

Here, a file handle/object is assigned to f directly. You close the file handle manually with the close method at the end.

Related Topic