Last active
October 5, 2020 02:18
-
-
Save rainyjonne/421afc62563c290b4057f60def995578 to your computer and use it in GitHub Desktop.
yml_to_tsv.rb 109078513
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
# frozen_string_literal: true | |
require 'csv' | |
require 'yaml' | |
# check file is tsv or not | |
def yml?(filename) | |
return raise('File not exist!') unless File.exist?(filename.to_s) # No file! | |
content = File.read(filename.to_s, encoding: 'utf-8') | |
return raise('Encoding Error!') unless content.valid_encoding? # Wrong encoding! | |
filename.include?('.yml') | |
end | |
input_yaml_file = ARGV[0] if yml?(ARGV[0]) | |
output_tsv_file = ARGV[1].to_s.include?('.tsv') ? ARGV[1] : raise('Output tsv file not found!') | |
def yml2tsv(input_yaml_file, output_tsv_file) | |
array_of_hashes = File.open(input_yaml_file) { |yf| YAML.safe_load(yf) } | |
CSV.open(output_tsv_file, 'w', { col_sep: "\t" }) do |tsv| | |
tsv << array_of_hashes.first.keys | |
array_of_hashes.each do |hash| | |
tsv << hash.values | |
end | |
end | |
end | |
yml2tsv(input_yaml_file, output_tsv_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment