为什么 RubyGems FasterCSV 将 [[1,3,5], [2,4,6]].to_csv 处理为“135,246\n”
下面的代码:
[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?
但需要这个:
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"
或更短:
data = [[1,3,5], [2,4,6]]
csv_string = FasterCSV.generate {|csv| data.each {|a| csv << a}}
=> "1,3,5\n2,4,6\n"
问题是,当给定一个数组数组时,为什么 to_csv
没有设计为自动处理它,以便在 Rails 中,我们可以这样做
respond_to do |format|
format.csv { render :text => data.to_csv }
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 }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
[[1,3,5], [2,4,6]].each{ |行| put line.to_csv } 还不错。如果您愿意,您可以随时覆盖 Array#to_csv。
我怀疑 FasterCSV 决定不实现这一点是因为很难绝对确定这就是程序员想要的。如果输入恰好是
[[1]、2、3、4]?仅查看外部数组的第一个元素就会让您认为它可能是数组的数组......
[[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...