Add the option :skip_blanks => true
when you are reading the CSV file.
file = CSV.read(path, :headers => true,:skip_blanks => true)
This option :skip_blanks => true
, will skip all such blank lines if any present like you are having, and you will get the normal output.
Here is my try for the same :
require 'csv'
content = <<_
key,fr
edit,éditer
close,Fermer
_
File.write('test',content)
file = CSV.read('test', :headers => true,:skip_blanks => true)
if file.headers() == nil
puts "According to the doc : Headers will not be used"
elsif file.headers() == true
puts "According to the doc : Headers will be used, but not read yet"
else
puts "Headers were read, this is an array : #{file.headers.to_s}"
end
# >> Headers were read, this is an array : ["key", "fr"]
Working correctly as you said, and I also agreed with you, below one :
require 'csv'
content = <<_
key,fr
edit,éditer
close,Fermer
_
File.write('test',content)
file = CSV.read('test', :headers => true)
file.headers # => ["key", "fr"]
file.to_a # => [["key", "fr"], ["edit", "éditer"], ["close", "Fermer"]]
When you set :headers => true
, the first row of the CSV data, you have will be tread as header. With this definition in mind, The above goes well. But the below one contradicts :
require 'csv'
File.write('test',content)
file = CSV.read('test', :headers => true)
file.headers # => ["key", "fr"]
file.to_a # => [["key", "fr"], ["edit", "éditer"], ["close", "Fermer"]]
content = <<_
key,fr
edit,éditer
close,Fermer
_
File.write('test1',content)
file = CSV.read('test1', :headers => true)
file.headers # => [] # <~~~~~~~~~~~ Is this a bug ?
file.to_a # => [[], [], ["edit", "éditer"], ["close", "Fermer"]]
file.headers
gives an empty array []
, as you can see that in the 0th index of the output of file.to_a
is also an empty array([]
). But it seems to a bug. Thus I raised the issue.