将结果保存到特定数据框的文件中?

时间:2013-11-21 00:56:16

标签: ruby-on-rails ruby save

当我尝试将输出保存到文本文件时,我遇到了一些问题:

def self.visual_model(object_or_ticker)

  predicted_values = DataVisual::test_model(object_or_ticker, opts={})


  myStr = predicted_values
  aFile = File.new("mydata.txt2", "w")
  aFile.write(myStr)
  aFile.close

  return predicted_values
end

predicted_values是一个数组,如下所示:

{:revenues=>[1, 2, 3, 4, 5], :cost=>[-8, -9, -8, 7, 3], :gross_profit=>[27, 26, 25, 25, 23]}

我想将文本文件保存为以下框架:

revenues      1, 2, 3, 4, 5
cost          -8, -9, -8, 7, 3
gross_profit  27, 26, 25, 25, 23

或者像这样:

  revenues    cost     gross_profit
    1           -8          27
    2           -9          26  
    3           -8          25    
    4           7           25
    5           3           23

1 个答案:

答案 0 :(得分:0)

output_string = ""
predicted_values.each do |key, value|
  output_string += "#{key.to_s.ljust(15," ")}#{value.join(", ")}\n"
end

File.open("predicted_values.txt", 'w') { |file| file.write(output_string) }