---
title: "IO#readlines now accepts chomp flag as an argument"
description:
  "IO methods now have an optional chomp flag to remove newline return
  characters"
canonical_url: "https://www.bigbinary.com/blog/io-readlines-now-accepts-chomp-flag-as-an-argument"
markdown_url: "https://www.bigbinary.com/blog/io-readlines-now-accepts-chomp-flag-as-an-argument.md"
---

# IO#readlines now accepts chomp flag as an argument

IO methods now have an optional chomp flag to remove newline return characters

- Author: Chirag Shah
- Published: March 7, 2017
- Categories: Ruby 2.4, Ruby

Consider the following file which needs to be read in Ruby. We can use the
`IO#readlines` method to get the lines in an array.

```plaintext

# lotr.txt

Three Rings for the Elven-kings under the sky,
Seven for the Dwarf-lords in their halls of stone,
Nine for Mortal Men doomed to die,
One for the Dark Lord on his dark throne
In the Land of Mordor where the Shadows lie.

```

### Ruby 2.3

```ruby

IO.readlines('lotr.txt')
#=> ["Three Rings for the Elven-kings under the sky,\n", "Seven for the Dwarf-lords in their halls of stone,\n", "Nine for Mortal Men doomed to die,\n", "One for the Dark Lord on his dark throne\n", "In the Land of Mordor where the Shadows lie."]

```

As we can see, the lines in the array have a `\n`, newline character, which is
not skipped while reading the lines. The newline character needs to be chopped
in most of the cases. Prior to Ruby 2.4, it could be done in the following way.

```ruby

IO.readlines('lotr.txt').map(&:chomp)
#=> ["Three Rings for the Elven-kings under the sky,", "Seven for the Dwarf-lords in their halls of stone,", "Nine for Mortal Men doomed to die,", "One for the Dark Lord on his dark throne", "In the Land of Mordor where the Shadows lie."]

```

### Ruby 2.4

Since it was a common requirement, Ruby team decided to
[add](https://bugs.ruby-lang.org/issues/12553) an optional parameter to the
`readlines` method. So the same can now be achieved in Ruby 2.4 in the following
way.

```ruby

IO.readlines('lotr.txt', chomp: true)
#=> ["Three Rings for the Elven-kings under the sky,", "Seven for the Dwarf-lords in their halls of stone,", "Nine for Mortal Men doomed to die,", "One for the Dark Lord on his dark throne", "In the Land of Mordor where the Shadows lie."]

```

Additionally, `IO#gets`, `IO#readline`, `IO#each_line`, `IO#foreach` methods
also have been modified to accept an optional chomp flag.

## Links

- [Human page](https://www.bigbinary.com/blog/io-readlines-now-accepts-chomp-flag-as-an-argument)
