Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to read a file line by line using the IO.foreach() in Ruby

okwudili onyejiaku

Overview

The IO instance is the basis for all input and output operations in Ruby. Using this instance, we can read a file and get its contents line by line using the foreach() method. This method takes the name of the file, and then a block which gives us access to each line of the contents of the file.

Syntax

IO.foreach(filename) {|x| # do something with each line x}
Syntax for the IO.foreach()

Parameters

filename: This represents the file we want to get its contents line by line.

x: This represents each line of the file that was provided by the block of the foreach() method.

Return value

The value returned is the contents of the file line by line.

Example

main.rb
text.txt
# create a file text.txt and read its contents line by line
IO.foreach("text.txt") {|x| puts x }
Using the foreach() method to read a file line by line

Explanation

  • Line 2: We create a file called text.txt and we manually write in some few texts, line by line. Then, we use the foreach() method of the IO instance, and inside our application file, we print each line of the file test.txt to the console.

Example

main.rb
text.txt
# create a file text.txt and read its contents line by line
IO.foreach("text.txt") {|x| puts "#{x.upcase}"  }
Print lines of a file one by one

Explanation

  • Line 2: We create a file called text.txt and we manually write in some texts, line by line. Then we use the foreach() method of the IO instance, and inside our application file, we print each line of the file test.txt to the console. Each line is a string of texts which we convert to uppercase and print to the console.

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring