我想通过 ruby 解析 csv 以创建报告

I would like to parse csv by ruby to create a report

我有一个包含两行的 csv 报告,其中 headers of "Date" & "Customer_name":

["Date", "Customer_Name"]
["Monday", "John"]
["", "David"]
["", "Sam"]
["", "Kenny"]
["Tuesday", "Mary"]
["", "Jade"]
["", "Lindsay"]
["Wednesday", "Tom"]
["", "Lindon"]
["", "Peter"]

我正在尝试打印一份声明以显示当天的客户是谁,因此它会显示如下:星期一有客户 John、David、Sam 和 Kenny。 \n 星期二有 Mary、Jade 和 Lindsay

我的代码是:

require 'csv'

col_date = []
col_name = []
custDate = CSV.foreach("customerVisit.csv") {|row| col_date << row[0]}
customer_name = CSV.foreach("customerVisit.csv") {|row| col_name << row[1]}

print "#{col_date} has customers #{col_name} visited the store."

但我没有得到正确的输出,很可能我是编程新手。请帮助我如何实现要求?

["Date", "Monday", nil, nil, nil, "Tuesday", nil, nil, "Wednesday", nil, nil] 有客户 ["Customer_Name", "John", "David", "Sam", "Kenny", "Mary", "Jade", "Lindsay", "Tom" , "Lindon", "Peter"] 访问了商店。C02S51D2G8WL:RubySQL

此致

您可以在此处找到结果的原因“#{array}”,它将数组 'as is' 插入到字符串中。所以你得到每组块。

我怀疑您使用了错误的工具来完成这项工作。 ruby 散列更适合对数据进行分类。 (至少这次)

例如

require 'csv'
customer_hash = {} # {"Date" => "Customers"}

temp = ""
CSV.foreach("customerVisit.csv") { |date, customer|
    temp = date if date
    customer_hash[temp] = [] unless customer_hash[temp]
    customer_hash[temp] << customer
}

customer_hash.each { |date, customers|
    print "#{date} has customers"
    customers.each { |name| print ", #{name}" }
    print "\nvisiting the store.\n"
}

这应该会在客户关联的那一天之后输出所有客户。

我出门在外,无法运行,我希望它能按预期工作>_<。

由于误读了您的数据样本,已编辑 代码。