为什么 RubyGems FasterCSV 将 [[1,3,5], [2,4,6]].to_csv 处理为“135,246\n”

发布于 2024-09-25 11:32:30 字数 698 浏览 3 评论 0原文

下面的代码:

[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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷默言语 2024-10-02 11:32:30

[[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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文