I am getting this error when I run the following code:
#!/usr/bin/env ruby -rubygems
require File.join(File.dirname(__FILE__), 'authentication')
require "csv" # faster_csv (ruby 1.9)
lines = CSV.read(File.join(File.dirname(__FILE__), 'karaoke.csv')) # Exported an Excel file as CSV
lines.slice!(0) # remove header line
collection = StorageRoom::Collection.find('collection ID')
Song = collection.entry_class
lines.each do |row|
karaoke = Song.new(:artist => row[0], :song => row[1], :genre => row[2], :file => StorageRoom::File.new_with_filename("#{karaoke.artist}#{karaoke.song}.mov"))
if karaoke.save
puts "Misuero Karaoke Latino saved: #{karaoke.artist}, #{karaoke.song}, #{karaoke.genre}"
else
puts "Misuero Karaoke Latino could not be saved: #{karaoke.errors.join(', ')}"
end
end
And the error is:
import_csv.rb:15:in `block in <main>': undefined method `artist' for nil:NilClass (NoMethodError)
from import_csv.rb:14:in `each'
from import_csv.rb:14:in `<main>'
I’m interested in learning why this error occurred as well as the solution. Thanks in advance!
Look at line 15 (
import_csv.rb:15tells you where to search for the issue):In the right part of assignment expression you use
karaoke.artistandkaraoke.songto construct:filepart of yourSong, butkaraokevariable is uninitialized yet (it appears on the left). In fact ruby interpreter definedkaraokevariable when it saw the assignment operator and started evaluation of right-hand part of assignment expression (to initialize variable) and failed, because defined variable hasnilvalue.