0

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 ?

1 Answer 1

2

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(',') }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.