chrisgeeq chrisgeeq - 1 year ago 77
Ruby Question

Float’: can’t convert nil into Float (TypeError)

am trying to read data from a csv file,but i keep getting this error "Float’: can’t convert nil into Float (TypeError)",below is my code and the text in the csv file.

"Date","ISBN","Price"

"2013-04-12","978-1-9343561-0-4",39.45

"2013-04-13","978-1-9343561-6-6",45.67

"2013-04-14","978-1-9343560-7-4",36.95

require 'csv'

require_relative 'book_in_stock'

class CsvReader
def initialize
@books_in_stock = []
end

def read_in_csv_data(csv_file)
CSV.foreach(csv_file, headers: true) do |row|
@books_in_stock << BookInStock.new(row["ISBN"], row["PRICE"])
end
end

def total_value_in_stock
sum = 0.0
@books_in_stock.each{|book| sum += book.price}
sum
end


end

class BookInStock
attr_reader :isbn, :price
#@amount = gets.chomp.to_i
def initialize(isbn,price)
@isbn = isbn
@price = Float(price)
end
end

kmz kmz
Answer Source

In the function read_in_csv_data you used upper case for addressing the row 'PRICE'. But in the CSV you had camel case 'Price' as the header.

So changing the BookInStock.new call parameter to row["Price"] solves the problem.

def read_in_csv_data(csv_file)
    CSV.foreach(csv_file, headers: true) do |row|
        @books_in_stock << BookInStock.new(row["ISBN"], row["Price"])
    end
end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download