ruby - How to use CSV.open and CSV.foreach methods to convert specific data in a csv file? -


the old.csv file contains these headers, "article_category_id", "articleid", "timestamp", "udid", of values in columns strings. so, trying convert them integers , store in csv file, new.csv. code:

require 'csv' require 'time'  csv.foreach('new.csv', "wb", :write_headers=> true, :headers =>["article_category_id", "articleid", "timestamp", "udid"]) |csv|     csv.open('old.csv', :headers=>true) |row|          csv['article_category_id']=row['article_category_id'].to_i         csv['articleid']=row['articleid'].to_i         csv['timestamp'] = row['timestamp'].to_time.to_i unless row['timestamp'].nil?          unless udids.include?(row['udid'])           udids << row['udid']         end         csv['udid'] = udids.index(row['udid']) + 1          csv<<row     end end 

but, getting following error: in 'foreach': ruby wrong number of arguments (3 1..2) (argumenterror).

when change foreach open, following error: undefined method '[]' #<csv:0x36e0298> (nomethoderror). why that? , how can resolve it? thanks.

csv#foreach not accept file access rights second parameter:

csv.open('new.csv', :headers=>true) |csv|   csv.foreach('old.csv',     :write_headers => true,      :headers => ["article_category_id", "articleid", "timestamp", "udid"]   ) |row|     row['article_category_id'] = row['article_category_id'].to_i     ...     csv << row   end end 

csv#open should placed before foreach. iterate old one , produce new one. inside loop should change row , append output.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -