2015-09-19 35 views
0

我在Ruby中學習CSV函數,雖然我可以成功將數組寫入csv文件,但我無法將該文件轉換回數組。測試代碼如下(我的應用程序只需要在數組中的整數)Ruby Reading CSV問題

require 'rubygems' 
requires 'csv' 
array = [1,2,3,4,5,6,7,8] 
CSV.open('array.csv', 'w') do |csv| 
csv << array 
puts array.inspect 
new_array = Array.new 
new_array = CSV.read('array.csv', converters: :numeric) 
puts new_array.inspect 
end 

這將返回

[1, 2, 3, 4, 5, 6, 7, 8] 
[] 

的array.csv文件寫入和填充(1,2,3,4,5, 6,7,8)但是當我讀它時,我只是返回一個空數組。

回答

4

在你的代碼的一些言論:

require 'rubygems'           #Not necessary 
requires 'csv'            #require instead requires 
array = [1,2,3,4,5,6,7,8] 
CSV.open('array.csv', 'w') do |csv| 
    csv << array 
    puts array.inspect 
    new_array = Array.new          #Not necessary 
    new_array = CSV.read('array.csv', converters: :numeric) #Called inside writing the CSV 
    puts new_array.inspect 
end 

你的主要問題是寫作過程中閱讀。你讀它之前先關閉CSV文件:

require 'csv'            
array = [1,2,3,4,5,6,7,8] 
CSV.open('array.csv', 'w') do |csv| 
    csv << array 
    puts array.inspect 
end 
new_array = CSV.read('array.csv', converters: :numeric) #Called inside 
puts new_array.inspect 

結果:

[1, 2, 3, 4, 5, 6, 7, 8] 
[[1, 2, 3, 4, 5, 6, 7, 8]]  

您的CSV可能包含多行,所以結果是在一個數組的數組。這是一個行數組(你有一個)。每行是一組元素。

2

您的CSV.open調用將創建文件,但其內容將被緩衝(即存儲在內存中而不是寫入磁盤),直到有足夠的數據寫入或關閉文件。您需要手動刷新底層文件對象,或者等到它關閉。

CSV.open('array.csv', 'w') do |csv| 
    #... 
end 
new_array = CSV.read('array.csv', converters: :numeric) 
puts new_array.inspect