4thSpace
4thSpace

Reputation: 44312

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
    end
end

Data in the file looks like this:

col1|col2|col3
col1|col2|col3
col1|col2|col3

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

'col3
'

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?

Upvotes: 0

Views: 114

Answers (1)

Cristian Lupascu
Cristian Lupascu

Reputation: 40546

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]}'"

Upvotes: 2

Related Questions