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.

# 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

IO . readlines ( '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."]

As we can see, the lines in the array have a

, 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.

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 an optional parameter to the readlines method. So the same can now be achieved in Ruby 2.4 in the following way.

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."]