Help us understand the problem. What is going on with this article?

[Ruby] CSVライブラリの使い方

More than 1 year has passed since last update.

csvファイルのよく使う扱い方をまとめました。

CSVファイルを新たに作成

require 'csv'

CSV.open('file.csv', 'w') do |csv|
  csv << ["id", "name", "location"]
  csv << [1, "hoge_1", "Kyoto"]
  # ...
end
file.csv
id,name,location
1,hoge_1,Kyoto
2,hoge_2,Osaka
3,hoge_3,Shiga
4,hoge_4,Fukui

CSVファイルの内容を追記

CSV.open('file.csv', 'a') do |csv|
  csv << [5, "hoge_5", "Nagano"]
end
file.csv
id,name,location
1,hoge_1,Kyoto
2,hoge_2,Osaka
3,hoge_3,Shiga
4,hoge_4,Fukui
5,hoge_5,Nagano

CSVファイルを読み込む

配列として扱う場合

CSV.read('file.csv')
# [["id", "name", "location"], ["1", "hoge_1", "Kyoto"] ... ]

ハッシュとして扱う場合( http://qiita.com/hkengo/items/59ba599ef48c613f2402

CSV.read('file.csv', headers: true)
#<CSV::Table mode:col_or_row row_count:5>

ハッシュからCSVファイル生成例

require 'csv'

module CSVConvertible
  def to_csv(*keys)
    keys = self.map(&:keys).inject([], &:|) if keys.empty?
    CSV.generate do |csv|
      csv << keys
      self.each { |hash| csv << hash.values_at(*keys) }
    end
  end
end

users = [
  {id: 1, name: 'hoge_1', location: 'Kyoto'},
  {id: 2, name: 'hoge_2', location: 'Osaka'},
  {id: 3, name: 'hoge_3', location: 'Shiga'},
  {id: 4, name: 'hoge_4', location: 'Fukui'}
].extend(CSVConvertible)

IO.write 'file.csv', users.to_csv
file.csv
id,name,location
1,hoge_1,Kyoto
2,hoge_2,Osaka
3,hoge_3,Shiga
4,hoge_4,Fukui

Railsの場合は、ActiveRecordのメソッドを使う。
http://qiita.com/retosu/items/5bda7bd5a55c20fc89c0

参考リンク

https://docs.ruby-lang.org/ja/latest/class/CSV.html
http://qiita.com/hkengo/items/59ba599ef48c613f2402
http://qiita.com/retosu/items/5bda7bd5a55c20fc89c0
http://qiita.com/metheglin/items/439d1fd9b0e0e53c6051

hkengo
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away