LoginSignup
33
20

More than 5 years have passed since last update.

[Ruby]CSV::Tableが便利

Last updated at Posted at 2017-02-19

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が返る

参考リンク

33
20
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
20