How to create multiple columns per row in CSV with Ruby
Ok, I have a hash that contains several properties. I wanted some properties of this hash to be added to the CSV file.
Here's what I wrote:
require 'csv'
require 'curb'
require 'json'
arr = []
CSV.foreach('test.csv') do | row |
details = []
details << result['results'][0]['formatted_address']
result['results'][0]['address_components'].each do | w |
details << w['short_name']
end
arr << details
end
CSV.open('test_result.csv', 'w') do | csv |
arr.each do | e |
csv << [e]
end
end
end
Everything works fine except that I get each one like this:
["something", "300", "something", "something", "something", "something", "something", "GB", "something"]
Like an array I don't want. I want each element of the array to be in a new column. The problem is I don't know how many elements I will have otherwise, I could have something like this:
CSV.open('test_result.csv', 'w') do | csv |
arr.each do | e |
csv << [e[0], e[1], ...]
end
end
end
Any ideas?
+3
source to share