DEV Community

Cover image for Ruby CSV Creator
Brandon Goodman
Brandon Goodman

Posted on

4 2

Ruby CSV Creator

I created this based on an API call that I parsed in the format of an array of hashes, like the example, in order to quickly generate a csv file for uploading.

# Run this file to auto generate a csv file based on the data passed in the products
# variable. I created this based on an API call that I parsed in the format of an array
# of hashes like the example in order to quickly generate a csv file for uploading.
require "csv"
products = [{"sku"=>"sku001", "name"=>"Item 1", "dimensions"=>"1 x 1 x 1"},
{"sku"=>"sku002", "name"=>"Item 2", "dimensions"=>"2 x 2 x 2"},
{"sku"=>"sku003", "name"=>"Item 3", "dimensions"=>"3 x 3 x 3"},
{"sku"=>"sku004", "name"=>"Item 4", "dimensions"=>"4 x 4 x 4"}]
CSV.open("new.csv", "wb") do |csv|
csv << ["Sku",
"Name",
"Dimensions"]
products.each do |product|
csv << ["#{product.assoc("sku")[1]}",
"#{product.assoc("name")[1]}",
"#{product.assoc("dimensions")[1]}"]
end
end
view raw csv_creator.rb hosted with ❀ by GitHub

https://gist.github.com/Brandongoodman615/42c0c1ee38ec1df0f0a698f05fe4044f

Top comments (0)

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay