0

I am learning the CSV function in Ruby and although I can successfully write an array into a csv file, I can not convert that file back into an array. Test code as follows (My application just requires integers in the array)

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

This returns

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

The array.csv file is written and populated (1,2,3,4,5,6,7,8) however I just return an empty array when I read it.

2 Answers 2

4

Some remarks on your code:

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

Your main problem is the reading inside the writing process. First close the CSV-file before you read it:

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

The result:

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

Your CSV may contain multiple lines, so the result is an array in an array. It is an array of lines (you have one). Each line is an array of elements.

Sign up to request clarification or add additional context in comments.

Comments

2

Your CSV.open call will create the file but its contents will be buffered (i.e. stored in memory rather than written to disk) until there is enough data to write or you close the file. You either need to manually flush the underlying file object or wait until it is closed.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.