在Ruby中将许多数组输出为CSV文件

时间:2014-06-30 18:05:21

标签: ruby csv export-to-csv

我对Ruby有疑问。我想要做的是首先对我的项目进行升序排序,然后将它们写入CSV文件。现在,由于我想迭代很多CSV文件,问题变得更加复杂。我发现这个thread并且答案看起来很好,但是我无法获得超过写入输出文件的最后一行。

如何将整个数据分类并写入不同的CSV文件?

我的代码:

require 'date'
require 'csv'

class Daily < 

  # Daily has a open
  Struct.new(:open)

  # a method to print out a csv record for the current Daily.

  def print_csv_record
    printf("%s,", open)
    printf("\n")
  end
end

#------#
# MAIN #
#------#

# This is where I iterate over my csv-files:
foobar = ['foo', 'bar']
foobar.each do |foobar|

# get the input filename from the command line
input_file = "#{foobar}.csv"

# define an array to hold the Daily records
arr = Array.new

# loop through each record in the csv file, adding
# each record to my array while overlooking the header.    
f = File.open(input_file, "r")
f.each_with_index { |row, i|
  next if i == 0
  words = row.split(',')
  p = Daily.new
  # do a little work here to convert my numbers
  p.open = words[1].to_f
  arr.push(p)
}

# sort the data by ascending opens
arr.sort! { |a,b| a.open <=> b.open }

# print out all the sorted records (just print to stdout)
arr.each { |p|
  CSV.open("#{foobar}_new.csv", "w") do |csv|
    csv << p.print_csv_record  
  end    
}
end

我的输入CSV文件:

Open
52.23
52.45
52.36
52.07
52.69
52.38
51.2
50.99
51.41
51.89
51.38
50.94
49.55
50.21
50.13
50.14
49.49
48.5
47.92

我的输出CSV文件:

47.92

1 个答案:

答案 0 :(得分:1)

您需要将迭代放在中打开的CSV文件:

CSV.open("#{foobar}_new.csv", "w") do |csv|
  arr.each { |p|
    csv << p.print_csv_record  
  }
end