require 'CSV' and nil rows

A

aidy

Hi,

I am reading a csv file using "require 'csv'". If the row == nil I
would like to move onto the next iteration.

This is the code

def enter_territories()
reader = CSV.open('C:\territory_data.csv', 'r')
header = reader.shift
reader.each{|row| next if row.nil?
STDERR.puts "row == #{row} "
p row
}
end

And this is the output

row == UNITED KINGDOMBRISTOLDE1SpringMA Portfolio23/05/2006null
["UNITED KINGDOM", "BRISTOL", "DE1", "Spring", "MA Portfolio",
"23/05/2006", "nu
ll", nil, nil, nil, nil, nil, nil]
row == UNITED KINGDOMBRISTOLDE2International ExpressMA
Portfolio23/05/2006null
["UNITED KINGDOM", "BRISTOL", "DE2", "International Express", "MA
Portfolio", "2
3/05/2006", "null", nil, nil, nil, nil, nil, nil]
row ==
[nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
row ==
[nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
row ==
[nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]
row ==
[nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil]

I cannot understand for the life of me why nil rows are being printed.
I have also used row.empty?

Cheers

Aidy
 
T

ts

a> def enter_territories()
a> reader = CSV.open('C:\territory_data.csv', 'r')
a> header = reader.shift
a> reader.each{|row| next if row.nil?

Well the problem is that `row' is an array with only nil values

You want Enumerable#any?

reader.each{|row| next unless row.any?

moulon% ruby -e 'a = [nil, nil]; puts "OK nil?" if a.nil?; puts "OK any?" unless a.any?'
OK any?
moulon%


a> STDERR.puts "row == #{row} "
 
A

aidy

Guy said:
reader.each{|row| next unless row.any?

Works perfectly.

I notice that the csv API has no documentation. Is this something that
could be added?

The API is perfect for testers who need to add much data.

Thank You

Aidy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top