What is IO.readlines() in Ruby?

Overview

The IO instance is used for all input and output operations in Ruby. When we use the readlines() method to read a file, it returns individual lines of a file as an array.

Syntax

IO.readlines(filename)
The readlines() method in Ruby

Parameters

  • filename: This is the name of the file.

Return value

This method returns an array containing individual lines of the file filename.

Code example

Let's look at the code below:

main.rb
text.txt
Welcome to edpresso
Please to meet you!
Happy learning!

Code explanation

We create a file named text.txt and write some contents in it:

  • Line 2: We use the readlines() method to get the contents of the file we created, line by line, as an array.
  • Line 5: We print this array to the console.

Free Resources