views:

28

answers:

1

the following code:

[1,3,5].to_csv
  => "1,3,5\n"       # this is good

[[1,3,5], [2,4,6]].to_csv
  => "135,246\n"     # why doesn't it just do it for array of array?

but require this instead:

data = [[1,3,5], [2,4,6]]
csv_string = FasterCSV.generate do |csv|
  data.each {|a| csv << a}  
end
 => "1,3,5\n2,4,6\n"

or shorter:

data = [[1,3,5], [2,4,6]]
csv_string = FasterCSV.generate {|csv| data.each {|a| csv << a}}
 => "1,3,5\n2,4,6\n"

The question is, when given an array of array, why is to_csv not designed to handle it automatically, so that in Rails, we can do

respond_to do |format|
  format.csv { render :text => data.to_csv }
+1  A: 

[[1,3,5], [2,4,6]].each{ |line| puts line.to_csv } isn't so bad. You could always override Array#to_csv if you wanted.

I suspect FasterCSV's decision to not implement that was because it is hard to be absolutely certain that's what the programmer will want. What if the input happens to be [[1], 2, 3, 4] ? Just looking at the first element of the outer array would make you think that it may be an array of arrays...

kwerle
how does `[[1,3,5], [2,4,6]].each{ |line| puts line.to_csv }` work with render? because you can render once only, i guess you will need to use `s += line.to_csv + "\n"`, or `(@data.map {|a| a.to_csv}).join("\n")`
動靜能量