require 'csv'
require 'yaml'
CSV.read (path_to_csv,: headers => true)
, an instance of CSV :: table class will be returned.
Extract the elements (instances of CSV :: Row class) one by one with the map
method, and hash the elements with the to_h
method. Since the return value of the map method is an array, an array with the hash as an element is created. The point is that the key name of the hash is the CSV column name by adding the : header => true
option this time.hash_arr = CSV.read(path_to_csv, :headers => true).map(&:to_h)
=>[{"region_id"=>"1", "country_id"=>"1", "region_name"=>"Hokkaido"}, {"region_id"=>"2", "country_id"=>"1", "region_name"=>"Aomori Prefecture"},...]
File.open(path_to_yaml, 'w') { |f| f.write(hash_arr.to_yaml) }
Postscript: It seems that the same writing can be done below. Thank you for your comment!
IO.write path_to_yaml, hash_arr.to_yaml
P.S As an aside from here, since I was managing a table (country or region) whose value is basically unchanged in the DB, I converted it this time to manage it with ActiveYaml. Even if it is managed by ActiveYaml, it is convenient because you can operate the table like ActiveRecord (class methods such as all and find can be used).
Recommended Posts