0

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?

Sean Lerner
  • 599
  • 1
  • 5
  • 14

1 Answers1

2

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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • Wow, glad it was my fault and not a problem with the csv file... thank you! – Sean Lerner Nov 15 '11 at 17:55
  • 2
    @sean: If you had warnings on, it would have warned you about `@filename_compare` being uninitialized. – Andrew Grimm Nov 15 '11 at 22:21
  • @Andrew: Oh how I wish warnings were enabled by default. Do we really have to learn this exact same lesson with every single language? – mu is too short Nov 15 '11 at 22:24
  • @muistooshort: Why not propose it for Ruby 2.0? – Andrew Grimm Nov 15 '11 at 22:26
  • 1
    @AndrewGrimm I will make sure to run my scripts with warnings on. Is there a way to have Ruby always run scripts with warnings (instead of calling scripts with `ruby -w script.rb`? I've been searching around and haven't come up with a way to do this. – Sean Lerner Nov 17 '11 at 20:48