4thSpace 4thSpace - 11 months ago 49
Ruby Question

How to cut end of line when reading files?

I'm reading the contents of a file into an array. The last item in a line is bringing the end of line character with it, which I don't want. Here's what I'm doing:

@arr = []
File.open('somefile.txt', 'r') do |file|
while (line = file.gets)
puts "'#{line.split('|')[2]}'"
@arr << line

Data in the file looks like this:


, it is including the end of line character. I can tell this from the above
, which outputs:



I've tried file.gets.chomp but that throws the following error:

undefined method `chomp' for nil:NilClass (NoMethodError)

How do I remove the end of line character?

Answer Source

Your code fails because when the file is read completely, file.gets returns nil, and calling .chomp on that throws the error you mentioned.

You could, however, call .chomp() inside the while block, where is it guaranteed that line is not nil.

For example, instead of

puts "'#{line.split('|')[2]}'"

you could do

puts "'#{line.chomp.split('|')[2]}'"