Skip to content

Instantly share code, notes, and snippets.

@makevoid
Created October 20, 2011 22:08
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save makevoid/1302537 to your computer and use it in GitHub Desktop.
Save makevoid/1302537 to your computer and use it in GitHub Desktop.
Convert Hashes to CSV easily
# 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
@tilo
Copy link

tilo commented Aug 8, 2012

to do the opposite: "convert CSV to Hashes", check this:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment