rubycsvspreadsheetroo-gemrubyxl

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


I have a csv report with two rows which has headers of "Date" & "Customer_name":

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

I am trying to print out a statement to show who is the customer for that day so it would show up like this: Monday has customers John, David, Sam, & Kenny. \n Tuesday has Mary, Jade and Lindsay

and my code is:

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."

But I am not getting the correct output and most likely iam new to programming.. Please help on how I should achieve the requirement?

["Date", "Monday", nil, nil, nil, "Tuesday", nil, nil, "Wednesday", nil, nil] has customers ["Customer_Name", "John", "David", "Sam", "Kenny", "Mary", "Jade", "Lindsay", "Tom", "Lindon", "Peter"] visited the store.C02S51D2G8WL:RubySQL

Regards


Solution

  • The reason for your result can be found here "#{array}", it inserts the array 'as is' into the string. So you get each set in chunks.

    I suspect you are using the wrong tool for the job. A ruby hash is better for categorizing data. (This time at least)

    For example

    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"
    }
    

    This should output all the customers after the day they are associated with.

    I'm away from home and unable to run this, I hope it works as intended >_<.

    Edited code due to miss-reading your data sample.