Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create multiple columns per row in CSV with Ruby

Tags:

ruby

csv

ruby-2.1

Ok, I have a hash which contains several properties. I wanted certain properties of this hash to be added to a CSV file.

Here's what I've written:

    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

All works fine apart from the fact the I get each like so:

["something", "300", "something", "something", "something", "something", "something", "GB", "something"]

As an array, which I do not want. I want each element of the array in a new column. The problem is that I do not know how many items I'll have otherwise I could 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?

like image 933
WagnerMatosUK Avatar asked Apr 29 '26 19:04

WagnerMatosUK


1 Answers

Change csv << [e] to csv << e.

like image 126
limekin Avatar answered May 01 '26 09:05

limekin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!