user3206440
user3206440

Reputation: 5049

storing array values into csv colums

I have a hash that needs to be written to a csv which is done via the code below.

require 'csv'

my_array = [ {name: 'Toyota', model: 'Corolla', engine: [ 4, 6]},{name: 'Honda', model: 'Civic', engine: [ 6, 8]} ]


CSV.open("my_csv.csv", "w", headers: my_array.first.keys, :write_headers => true) do |csv|
  my_array.each do |hash|
    csv << hash.values
  end
end

As you would see there is an array of values stored in one of the keys - engine. In my csv it looks like below.

name,model,engine
Toyota,Corolla,"[4, 6]"
Honda,Civic,"[6, 8]"

Instead of having the engine column in the above format like "[4, 6]", how can I get it like 4,6 while keeping the csv formatting. What is the typical convention when one have to store an array of values in a csv column ?

Upvotes: 0

Views: 41

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

There is no “typical convention” of storing arrays (and any other objects) in CSV columns. CSV is supposed to store text values.

If you want to have them in the single column, just join the array:

csv << hash.values.map { |e| [*e].join(',') }

Upvotes: 2

Related Questions