Created
February 4, 2020 08:25
-
-
Save majedbojan/89daf44e4055ac6dcfdbadec7c222de9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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