IO#readlines now accepts chomp flag as an argument

Chirag Shah

Chirag Shah

March 7, 2017

This blog is part of our  Ruby 2.4 series.

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.

1
2# lotr.txt
3
4Three Rings for the Elven-kings under the sky,
5Seven for the Dwarf-lords in their halls of stone,
6Nine for Mortal Men doomed to die,
7One for the Dark Lord on his dark throne
8In the Land of Mordor where the Shadows lie.
9

Ruby 2.3

1
2IO.readlines('lotr.txt')
3#=> ["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."]
4

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.

1
2IO.readlines('lotr.txt').map(&:chomp)
3#=> ["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."]
4

Ruby 2.4

Since it was a common requirement, Ruby team decided to add an optional parameter to the readlines method. So the same can now be achieved in Ruby 2.4 in the following way.

1
2IO.readlines('lotr.txt', chomp: true)
3#=> ["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."]
4

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

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.