ASCII Delimited Text in Ruby - an implementation of https://ronaldduncan.wordpress.com/2009/10/31/text-file-formats-ascii-delimited-text-not-csv-or-tab-delimited-text/
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
require 'csv' | |
data = [ | |
{ | |
:name => "Joe", | |
:age => 30, | |
:description => "\"Joe's a great guy.\" - most of his friends say" | |
}, | |
{ | |
:name => "Bob", | |
:age => 42.1, | |
:description => "Bob's personality goes from here:\t\t\t\t\t: to there\nYa know?" | |
} | |
] | |
options = { | |
:col_sep => 31.chr, | |
:row_sep => 30.chr, | |
:quote_char => ' ', # the CSV library doesn't like when this is blank | |
:headers => true, | |
:header_converters => :symbol, | |
:converters => :all | |
} | |
# data -> csv | |
header = nil | |
csv_data = CSV.generate(options) do |csv| | |
header = data.first.keys | |
csv << header | |
data.each{|row| | |
csv << row.values | |
} | |
end | |
puts "CSV:" | |
puts csv_data | |
puts | |
# csv -> data | |
parsed_data = CSV.parse(csv_data, options).map{|row| | |
Hash[row.map{|c,r| | |
[c,r] | |
}] | |
} | |
puts "Parsed data:" | |
p parsed_data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment