Skip to content

Instantly share code, notes, and snippets.

@majedbojan
Created February 4, 2020 08:25
Show Gist options
  • Save majedbojan/89daf44e4055ac6dcfdbadec7c222de9 to your computer and use it in GitHub Desktop.
Save majedbojan/89daf44e4055ac6dcfdbadec7c222de9 to your computer and use it in GitHub Desktop.
def csv(data)
arr = Array.wrap(data)
CSV.open(csv_filename, 'wb') do |csv|
keys = arr.first.keys
# header_row
csv << keys
arr.each do |hash|
csv << hash.values_at(*keys)
end
end
end
# Usage
# You can send either array or hash it should convert to CSV
# csv([{first_name: 'Ahmed', last_name: 'Ali'}, {first_name: 'Mohammed', last_name: 'majed'}])
# OR add this method in array class config/initializers/array.rb
class Array
def to_csv(csv_filename='hash.csv')
require 'csv'
CSV.open(csv_filename, 'wb') do |csv|
csv << first.keys
self.each do |hash|
csv << hash.values_at(*keys)
end
end
end
end
# Usage
# [{first_name: 'Ahmed', last_name: 'Ali'}, {first_name: 'Mohammed', last_name: 'majed'}].to_csv('file_name.csv')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment