DEV Community

Discussion on: CSV Challenge

Collapse
 
rpalo profile image
Ryan Palo

Using the CSV module to avoid any quoting pitfalls. :)

require 'CSV'
require 'date'
require 'JSON'

data = JSON.parse(`curl #{ARGV[0]}`)
filename = Date.today.strftime('%Y%m%d') + '.csv'

CSV.open("#{filename}.csv", 'w') do |csv|
  data
    .select { |item| item['name'] && item['creditcard'] }
    .map { |item| [item['name'], item['creditcard']] }
    .sort
    .each { |item| csv << item }
end
Collapse
 
jorinvo profile image
jorin • Edited

Ruby is still one of the most pretty languages!
Maybe you can use the open(url).read from require 'open-uri' instead of curl to allow it to run on other systems 🙂

Alernatively could look like this:

CSV.open "#{Date.today.strftime '%Y%m%d'}.csv", 'w' do |csv|
  JSON.parse(open(ARGV[0]).read).each { |x| csv << x if x['creditcard'] }
end
Collapse
 
rpalo profile image
Ryan Palo

Oh, I like that!

  1. I didn't know about those extra options for CSV. Awesome.
  2. I didn't know about the open-uri built-in. Also awesome.
  3. I love the short and sweet each block! It even feels a little Pythonic, which is nice. Also also awesome!