Arrayのjoinメソッドを利用するととても簡単にCSV形式で出力することができます。
以下のサンプルコードはカンマ区切りにしていますが、joinメソッドに渡す値を変更すれば他の文字することも可能です。
htmlinsert(): The given local file does not exist or is not readable.
以下に3種類のサンプルコードを記します。
以下のような配列の場合は、1行のCSVを出力します。
ary = ['red', 'green', 'blue'] ary.join(",")
$ ruby join-1.rb red,green,blue
以下のように配列内にCSVにしたい配列が複数行格納されている場合は以下のようにします。
ary = [['red', 'green', 'blue'], ['linux', 'windows', 'macosx']] ary.each {|v| puts v.join(",") }
$ ruby join-2.rb red,green,blue linux,windows,macosx
先頭に番号をつけたい場合は、each.with_indexを使用すれば可能です。
(each.with_indexをeach_with_indexに置き換えても同等の結果になります)
ary = [['red', 'green', 'blue'], ['linux', 'windows', 'macosx']] ary.each.with_index {|v, i| puts "#{i+1},#{v.join(",")}" }
$ ruby join-3.rb 1,red,green,blue 2,linux,windows,macosx