Float':无法将nil转换为Float(TypeError)

时间:2017-05-22 19:03:38

标签: ruby csv

我正在尝试从csv文件中读取数据,但我一直收到此错误" Float':无法将nil转换为Float(TypeError)",下面是我的代码和文本中的csv文件。

csv文件

"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

CsvReader类

    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

BookInStock类

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

1 个答案:

答案 0 :(得分:1)

在函数read_in_csv_data中,您使用大写字母来寻址 行&#39;价格&#39;但在CSV中你有骆驼案例&#39; Price&#39;作为标题。

因此,将BookInStock.new调用参数更改为row [&#34; Price&#34;]可以解决问题。

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