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

[Ruby]CSV::Tableが便利

More than 1 year has passed since last update.

CSV::Table

行単位や列単位の操作が簡単にできる!

require 'csv'
table = CSV.table('./test.csv')
table.headers  #=> [:id, :name, :uid, :created_at]

列でデータが取れます。

row = table.first
row[:id]    #=> [1, 2, 3, ...]
row[:name]  #=> [taro, ryota, kengo, ...]

ループで処理する際も、ハッシュで管理できて楽です。

table.each do |row|
  puts "row[:id] row[:name] row[uid]"  #=> 1 taro 28c762c8ab6c84d8380496ede2599d00
end

CSV <==> CSV::Table の変換もできる!

CSV => CSV::Table に変換

csv = CSV.new('./test.csv', headers: true)
table = csv.read
table.inspect # => "#<CSV::Table mode:col_or_row row_count:2>"

CSV::Table => CSV に変換

csv = CSV.new('./test.csv', headers: true)
table = csv.read
table.to_csv                       #=> csvが返る 
table.to_csv(write_headers: false) #=> ヘッダーなしのcsvが返る

参考リンク

https://docs.ruby-lang.org/ja/latest/class/CSV=3a=3aTable.html

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