ruby - Parse CSV File, Take Input From Columns, Output to A New Column and Export to a new CSV -
ruby - Parse CSV File, Take Input From Columns, Output to A New Column and Export to a new CSV -
i have csv has 7-8 columns of data.
for each row, want 1) take value of 2 of columns 2) utilize values in method have defined 3) add together output new column 4) delete original 2 columns 5) export new csv
i'm extremely new ruby , programming in general, , can't seem find answers (that can understand) on how this.
an illustration of have this:
csv headers: title, day, date, time illustration values: fun in sun, wed, 09/11/14, 3:00 pm
the methods i've (tried write) combine date , time:
def convert_time (time) time_array = time.split(" ") time_numbers = time_array[0] time_mod = time_array[1] time_numbers = time_numbers.split("") if time_mod == "pm" time_numbers[0] = (time_numbers[0].to_i + 12).to_s end time_numbers.join("") end def add_date (date, time) # 09/11/14 -> 20140911 date_array = date.split("/") new_date = "2014" + date_array[0] + date_array[1] output = "tzid=america/los angeles:#{new_date}" + "t" + convert_time(time) end
i want take values in csv file (date , time) , add together them parameters in add_date method value add together csv in new column
any help or pointers in right direction appreciated.
without seeing snip-it of csv file, can't give exact answer. can, however, utilize csv file made should data. you'll have fill in gaps wherever are.
i've never dealt parsing csv files in ruby before, i'll step through problem solving process , illustrates how can solve type of problem in future.
first off, here csv file i'm using:
title, day, date, time fun in sun, wed, 09/11/14, 3:00 pm
a quick google search of ruby csv
yields documentation ruby's csv parsing class: http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/csv.html.
further googling ruby csv headers
yields stack overflow post: ruby parse csv file header fields attributes each row
great, can this:
csv.foreach('my_file.csv', :headers => true) |csv_obj| # access csv info here end
looking @ documentation csv class, can write info csv. finally, can solve problem:
def add_date (date, time) # 09/11/14 -> 20140911 date_array = date.split("/") new_date = "2014" + date_array[0] + date_array[1] output = "tzid=america/los angeles:#{new_date}" + "t" + convert_time(time) end csv.open('output_file.csv', 'wb') |csv_out| csv.foreach('input_file.csv', :headers => true) |csv_in| csv_out << [csv_in['title'], csv_in['day'], add_date(csv_in['date'], csv_in['time'])] end end
make sense?
ruby csv export-to-csv
Comments
Post a Comment