使用 Ruby 将数组写入多列 CSV 格式

Write an array to multi column CSV format using Ruby

我在 Ruby 中有一个数组,我正试图将其输出到 CSV 文件(或文本)。然后我可以轻松地转移到另一个 XML 文件进行绘图。

我似乎无法像这样获得输出(文本格式)。相反,我得到一行数据,这只是一个大数组。

0,2
0,3
0,4
0,5

我最初尝试了类似的方法

File.open('02.3.gyro_trends.text' , 'w') { |file| trend_array.each { |x,y| file.puts(x,y)}}

它输出

0.2
46558
0
46560
0
....etc etc.

任何人都可以为我指明 "write" 的方向以获得:

(i) 可以像这样放置我的数据的.text 文件。

trend_array[0][0], trend_array[0][1] 
trend_array[1][0], trend_array[1][1] 
trend_array[2][0], trend_array[2][1] 
trend_array[3][0], trend_array[3][1] 

(ii) .csv 文件,将此数据放在单独的列中。
edit 我最近在我的数组中添加了两个以上的值,请查看我结合 Cameck 解决方案的答案。

这是我目前拥有的。

trend_array=[]
j=1

# cycle through array and find change in gyro data.

while j < gyro_array.length-2

  if gyro_array[j+1][1] < 0.025 && gyro_array[j+1][1] > -0.025
    trend_array << [0, gyro_array[j][0]]
    j+=1
  elsif gyro_array[j+1][1] > -0.025  # if the next value is      increasing by x1.2 the value of the previous amount. Log it as +1
    trend_array << [0.2, gyro_array[j][0]]
    j+=1
  elsif gyro_array[j+1][1] <  0.025 # if the next value is   decreasing by x1.2 the value of the previous amount. Log it as -1
    trend_array << [-0.2, gyro_array[j][0]]
    j+=1
  end
end

#for graphing and analysis purposes (wanted to print it all as a csv  in two columns)

File.open('02.3test.gyro_trends.text' , 'w') { |file| trend_array.each { |x,y| file.puts(x,y)}}

File.open('02.3test.gyro_trends_count.text' , 'w') { |file| trend_array.each {|x,y| file.puts(y)}}

我知道这很容易,但出于某种原因我错过了。有连接的东西,但我发现如果我尝试在最后一行代码中连接 \n,它不会将它输出到文件中。它以我想要的方式在我的控制台中输出它,但不是在我将它写入文件时。

感谢您花时间阅读所有内容。

File.open('02.3test.gyro_trends.text' , 'w') { |file| trend_array.each { |a| file.puts(a.join(","))}}

交替使用 CSV Class:

  def write_to_csv(row)
    if csv_exists?
      CSV.open(@csv_name, 'a+') { |csv| csv << row }
    else
      # create and add headers if doesn't exist already
      CSV.open(@csv_name, 'wb') do |csv|
        csv << CSV_HEADER
        csv << row
      end
    end
  end

  def csv_exists?
    @exists ||= File.file?(@csv_name)
  end

用数组调用write_to_csv[col_1, col_2, col_3]

谢谢@cameck 和@tkupari,这两个答案都是我想要的。最后选择了 Cameck 的答案,因为它 "cut out" 剪切和粘贴文本 => xml。这是我将数组数组放到适当位置所做的工作。

require 'csv'

CSV_HEADER = [
                "Apples",
                "Oranges",
                "Pears"
                        ]

@csv_name = "Test_file.csv"

def write_to_csv(row)
  if csv_exists?
    CSV.open(@csv_name, 'a+') { |csv| csv << row }
  else
    # create and add headers if doesn't exist already
    CSV.open(@csv_name, 'wb') do |csv|
      csv << CSV_HEADER
      csv << row
    end
  end
end

def csv_exists?
  @exists ||= File.file?(@csv_name)
end

array = [ [1,2,3] , ['a','b','c'] , ['dog', 'cat' , 'poop'] ]
array.each { |row| write_to_csv(row) }