From: cristian cristian Date: 2012-04-19T05:26:26+09:00 Subject: Re: Converting CSV Eric C. wrote in post #1057247: > Hi Christian: > > The way you loop through the array, is with a Ruby iterator. The method > "each" will iterate through anything generally: > > require 'fastercsv' > array_of_arrays = FasterCSV.read("myfile.csv") > > new_file = FasterCSV.new() > array_of_arrays.each do | item | > new_file.add_row(item) > end > File.open("saved_file.csv", "w") { |f| new_file.dump } > > It seems to me that there must be a better way to do what you're trying > to accomplish. I don't know why you'd want to mess-around with csv > files in the first place. I don't understand why the comma delimited > csv file is better than the original. You could just use the original. > > Also, if you're just doing a simple conversion, I'd just use simple ruby > code instead of having to learn everything about the CSV stuff: > > File.open("original_file.txt", "r") do |f| > new_file = File.open("new_file.csv", "w") > f.each_line do |line| > fields = line.split(";") > fields.each { |fd| fd = "\"#{fd}\"" > new_file.write(fields.join(",") > end > new_file.close > end > > Perhaps if you explain what you're trying to do with these files, I > could give you better advise. Ruby has many tools to save objects like > YAML and JSON. Generally its better not to mess around with formatting > files yourself. Hi! The files are to be read by some system that cannot handle csv files with semicolon. The problem is that the fields might contain commas also. So the file should be comma separated with quoted fields. I get these error messages with your last example: CSVConverter.rb:7: syntax error, unexpected kEND, expecting ')' CSVConverter.rb:9: syntax error, unexpected kEND, expecting '}' Br cristian -- Posted via http://www.ruby-forum.com/.