【发布时间】:2017-06-18 16:16:34
【问题描述】:
我在 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.
谁能指出我的“写”方向来获得:
(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 文件,该文件会将这些数据放在单独的列中。
编辑我最近在我的数组中添加了两个以上的值,请结合 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,它不会将其输出到文件中。它以我想要的方式在我的控制台中输出它,但不是在我将它写入文件时。
感谢您花时间阅读这一切。
【问题讨论】:
标签: ruby export-to-csv file-writing