[Ruby] [Ruby] How to convert CSV file to Yaml (Yml)

1 minute read


  1. Require the Ruby standard library csvandyml.
  1. When you execute CSV.read(path_to_csv, :headers => true), an instance of CSV::table class will be returned. The elements (CSV::Row class instances) are fetched one by one with the map method, and the elements are hashed with the to_h method. Since the return value of map method is an array, an array with hash as an element is created. This time, the point is that the key name of the hash becomes the column name of CSV by adding the :header => true option.
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"},...]
  1. Open the file specified by path in write mode, convert the array with the hash of 2 as an element to Yaml and save it.
File.open(path_to_yaml,'w') {|f| f.write(hash_arr.to_yaml)}

Postscript: It seems that the same writing can be done with the following. Thank you for your comment!

IO.write path_to_yaml, hash_arr.to_yaml


As an aside from here, I basically managed a table (country or region) whose value does not change in DB, so I converted this time to manage it with ActiveYaml. Even if managed by ActiveYaml, it is convenient because you can operate the table like ActiveRecord (class methods such as all and find can be used).