What is the file.each{} method in Ruby?

Overview

The each{} method of the file instance is used to get each line of the file content.

Syntax

Let's view the syntax of this method.

File.each {|line| }
Syntax for each{}

Parameters

line: This represents each line of the file content. It is provided by the each{} method.

Return value

Each line of the file content is returned.

Code example

Let's view a code example below.

main.rb
test.txt
# get file or create new file
f = File.new("test.txt")
# print each line
f.each {|line| puts "#{f.lineno}: #{line}"}

Explanation

  • Line 1: We create a file called test.txt and write some text to it.
  • Line 2: We get the file.
  • Line 5: We use the each{} method and f.lineno to print each line number and each line of the file, respectively.

Free Resources