如何对csv行求和
how to sum rows of csv
我有以下从 txt 文件中检索行的代码,我想对 item_price 的所有值求和以便能够在我的应用程序中使用它。我希望从块中检索此值:
CSV.foreach(dir, col_sep: "\t", headers: true).map do |row|
关注代码:
module ParseText
def self.parse
require 'csv'
dir = Dir.glob("./public/system/file_attaches/files/*/*/*/*/*").max_by {|f| File.mtime(f)}
CSV.foreach(dir, col_sep: "\t", headers: true).map do |row|
records = row.to_h
purchaser = records["purchaser name"]
item_description = records["item description"]
item_price = records["item price"]
purchase_count = records["purchase count"]
merchant_address = records["merchant_address"]
merchant_name = records["merchant name"]
Merchant.create(name: merchant_name)
MerchantAddress.create(street: merchant_address, merchant_id: Merchant.last.id)
Purchaser.create(name: purchaser, count: purchase_count, merchant_id: Merchant.last.id)
Item.create(description: item_description, price: item_price, merchant_id: Merchant.last.id, purchaser_id: Purchaser.last.id )
end
end
end
CSV.foreach(dir, col_sep: "\t", headers: true).inject(0) do |price_sum, row|
# Leave the code you already have here
price_sum += item_price.to_i
end
我有以下从 txt 文件中检索行的代码,我想对 item_price 的所有值求和以便能够在我的应用程序中使用它。我希望从块中检索此值:
CSV.foreach(dir, col_sep: "\t", headers: true).map do |row|
关注代码:
module ParseText
def self.parse
require 'csv'
dir = Dir.glob("./public/system/file_attaches/files/*/*/*/*/*").max_by {|f| File.mtime(f)}
CSV.foreach(dir, col_sep: "\t", headers: true).map do |row|
records = row.to_h
purchaser = records["purchaser name"]
item_description = records["item description"]
item_price = records["item price"]
purchase_count = records["purchase count"]
merchant_address = records["merchant_address"]
merchant_name = records["merchant name"]
Merchant.create(name: merchant_name)
MerchantAddress.create(street: merchant_address, merchant_id: Merchant.last.id)
Purchaser.create(name: purchaser, count: purchase_count, merchant_id: Merchant.last.id)
Item.create(description: item_description, price: item_price, merchant_id: Merchant.last.id, purchaser_id: Purchaser.last.id )
end
end
end
CSV.foreach(dir, col_sep: "\t", headers: true).inject(0) do |price_sum, row|
# Leave the code you already have here
price_sum += item_price.to_i
end