Sean Lerner
Sean Lerner

Reputation: 599

How to get around "Can't convert nil into String (TypeError)" when reading a csv file in Ruby?

I am working on a program that will eventually compare two .csv files and print out any variances between the two. However, at the moment I can't get past a "can't convert nil into String (TypeError)" when reading one of the files.

Here is a sample line from the problematic csv file:

11/13/15,11:31:00,ABCD,4000150097,1321126281700ABCDEF,WR00002440,,,4001,1392,AI,INTERNAL RETURN,INBOUND,,ABCDEF

And here is my code so far:

require 'csv'
class CSVReportCompare

  def initialize(filename_data, filename_compare)
    puts "setting filename_data=", filename_data
    puts "setting compare=", filename_compare
    @filename_data = filename_data
    @filenam_compare = filename_compare
  end

  def printData
    @data = CSV.read(@filename_data)
    puts @data.inspect
  end

  def printCompareData
    @compareData = CSV.read(@filename_compare)
    puts @compareData.inspect
  end

  def compareData

  end

end

c1 = CSVReportCompare.new("data.csv", "compare_data.csv")
c1.printData
c1.printCompareData

Anyways, is there a way to get around the error?

Upvotes: 0

Views: 3769

Answers (1)

mu is too short
mu is too short

Reputation: 434675

You have a typo in your initialize method:

@filenam_compare = filename_compare
#-------^ missing "e"

So you're setting the wrong instance variable. Instance variables are created when they're first used and initialized to nil so later, when you try to access @filename_compare, the instance variable with the correct name is created and has a value of nil.

Upvotes: 2

Related Questions