0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

rails CSV.open とCSV.generateの使う場面の違い CSV

Last updated at Posted at 2020-05-22

CSV.open とCSV.generateの使う場面の違い

  • csvの使い方を調べると、CSV.open が多い
  • 会社の実装を見てみるとCSV.generateが多い気がする

なぜ場面によって違うのか?

csvの出力先を【ディレクトリ配下に置く】のか。【export】するのか(railsで)によって異なるのかな。

## CSV.open
### これはopenの第一引数の指定先(output.csv)に出力する事を想定している
### 実行 すると同じディレクトリ配下に ls csv_ruby.rb output.csvみたいになる

csv_ruby.rb # ファイル名

lists = [["1","2","3"],["4","5","6"]]

CSV.open("./output.csv", "w") do |row|
  lists.each do
    row << list 
  end
end

## CSV.generate


lists = [["1","2","3"],["4","5","6"]]

csvs = CSV.generate do |row|
  lists.each do |list|
    row << list 
  end
end

## これは出力結果を なにかしらの変数に入れて中身を確認する必要がある

## 最終的にsenddataの引数に渡してダウンロードする

def index
 format.csv do
   sendata(csvs, type: :csv, failename: "ファイル名")
 end
end

まとめ

こんな感じで、最終的な期待結果に応じて、csvの作り方が異なる

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?