0

I am trying to split a row from a CSV file into an array. I can print out all the contents from the CSV file to the console no problem, like this:

CSV.foreach('so1.csv', :headers => true, :col_sep => "\t", :skip_blanks => true) do |row|
  id, name = row[0], row[1]
  puts id, name
end

However, when I try to split name i.e. row[1] into an names array, I get a undefined method 'split' for nil:NilClass (NoMethodError) message:

CSV.foreach('so1.csv', :headers => true, :col_sep => "\t", :skip_blanks => true) do |row|
  id, name = row[0], row[1]
  unless (id =~ /#/)
    names = name.split
  end

I have also tried name.split("\n") and name.split("\t") to no avail.

For clarity, a screenshot of the CSV file:

CSV Screenshot

CSV Screenshot

Could anybody shed any light on what is going wrong here? It would be great - thanks.

4

1 回答 1

2

It's telling you that name is nil, probably because row[1] doesn't exist. My guess is the columns aren't being split properly. Right now you're saying that columns are separated by tabs but that's not what the screenshot is showing.

Are you sure you don't want :col_sep => ","?

于 2013-10-10T20:30:38.960 回答