Created
October 20, 2011 22:08
-
-
Save makevoid/1302537 to your computer and use it in GitHub Desktop.
Convert Hashes to CSV easily
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
# Convert Hashes to CSV easily | |
# source.rb | |
# | |
# { valid: "ruby", hash: "" } | |
# { another: "valid", ruby: "hash" } | |
# { etc... | |
# usage: | |
# | |
# Csv.new.start | |
# | |
# | |
# then take a look at output.csv | |
require_relative "env" | |
class Csv | |
SEP = "," | |
PATH = File.expand_path "../", __FILE__ | |
DEFAULT_PATH = "#{PATH}/source.rb" | |
CSV_PATH = "#{PATH}/output.csv" | |
def initialize(file=nil, csv_path=nil) | |
@file = file || DEFAULT_PATH | |
@csv_path = csv_path || CSV_PATH | |
end | |
def start | |
cont = File.read(@file) | |
nomins = eval "[#{cont.split("\n").join(",")}]" | |
File.open(@csv_path, "w"){ |f| f.write "" } | |
File.open @csv_path, "a" do |csv| | |
csv.puts header(nomins.first) | |
nomins.each do |nomin| | |
nome = to_csv nomin | |
csv.puts nome | |
end | |
end | |
end | |
private | |
def header(hash) | |
hash.keys.join SEP | |
end | |
def to_csv(hash) | |
hash.values.map do |value| | |
escape value unless value.nil? | |
end.join SEP | |
end | |
def escape(string) | |
string.gsub(SEP, "\SEP") | |
end | |
end | |
# Csv.new.start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
to do the opposite: "convert CSV to Hashes", check this: