The following code reads and outputs text in a file.

Demo"main.rb").each { |line| puts line }


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"main.rb", "r").each { |line| puts line }


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 can accept a code block, and once the block is finished, the file will be closed automatically. returns a File object referring to the file.

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

First, look at

Demo"main.rb") do |f| 
  puts f.gets 

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 approach:


f ="main.rb", "r") 
puts f.gets 

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