簡體   English   中英

在Ruby中從帶有標頭的CSV加載數據

[英]Loading data from a CSV with header in Ruby

我想加載CSV文件並基於數據創建對象。 該文件具有以下結構:

product code;product name;product price;units
RTF0145;Mixer;659;15
GTF4895;PC;9999;25

加載數據時,我想跳過帶有標題的第一行,但是使用{:headers => true}屬性時遇到麻煩,該方法不執行任何操作,不會引發任何錯誤。

def Store.load_data(file, separator, headers = true)
  begin
    @items = []
    CSV.open(file, "r", {:col_sep => separator}, {:headers => headers}) do |csv|
      csv.each do |product|
        @items << Store.new(product["product code"], product["product name"], product["price"], product["units"])
      end
    end
  rescue
  end
end

我這樣調用方法:

Store.load_data("products.csv", ";")

如果我不使用headers參數,則一切正常。

  def Store.load_data(file, separator, headers = true)
    begin
      @items = []
      CSV.foreach(file, { :col_sep => separator }) do |row|
        @items << Store.new(row[0], row[1], row[2], row[3]) unless row[0] == "product code"
      end
    rescue
    end
  end

CSV.open方法的簽名為:

CSV.open(filename, mode = "rb", options = Hash.new)

因此,這樣調用它:

CSV.open(file, "r", { ... }, { ... }) 

...是不正確的,並且Ruby應該在執行此操作時引發異常。

用哈希調用CSV.open的正確方法是:

CSV.open(file, "r", { :a => b, :c => d, :e => f })

要么:

CSV.open(file, "r", :a => b, :c => d, :e => f)

因此,要解決您的問題,解決方案應該是更改此設置:

CSV.open(file, "r", { :col_sep => separator }, { :headers => headers })

對此:

CSV.open(file, "r", { :col_sep => separator, :headers => headers })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM