Skip to content

Instantly share code, notes, and snippets.

@amonmoce
Last active August 29, 2015 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amonmoce/76acd162f17dbfbd9193 to your computer and use it in GitHub Desktop.
Save amonmoce/76acd162f17dbfbd9193 to your computer and use it in GitHub Desktop.
A Ruby code that convert tsv file into yaml file ... like $ruby tsv_to_yaml.rb in_filename.tsv out_filename.yml; Rubocop tested no offense
# Check the output file
if ARGV[1].nil?
print 'Insert the name of your output file (yml file) '
outname = $stdin.gets.chomp
else
outname = ARGV[1]
end
# Build the array of Hashes
require 'yaml'
survey = []
lines = []
tsv_file = File.open(ARGV[0], 'r')
tsv_file.each_line { |line| lines << line }
tsv_file.close
keys = lines[0].split("\t")
keys.map!(&:chomp)
lines.shift
lines.each do |line|
values = line.split("\t")
record = Hash.new
keys.each_index { |index| record[keys[index]] = values[index].chomp }
survey.push(record)
end
# Serialize the data
File.open(outname, 'w') do |file|
file.puts survey.to_yaml
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment