Ruby 2.4.0 リファレンスマニュアル > ライブラリ一覧 > csvライブラリ > CSVクラス

class CSV

クラス・モジュールの継承リスト: CSV < Enumerable < Object < Kernel < BasicObject
extend: Forwardable

要約

このクラスは CSV ファイルやデータに対する完全なインターフェイスを提供します。

読み込み


require "csv"

csv_text = <<~CSV_TEXT
  Ruby,1995
  Rust,2010
CSV_TEXT

IO.write "sample.csv", csv_text

# ファイルから一行ずつ
CSV.foreach("sample.csv") do |row|
  p row
end
# => ["Ruby", "1995"]
#    ["Rust", "2010"]

# ファイルから一度に
p CSV.read("sample.csv")
# => [["Ruby", "1995"], ["Rust", "2010"]]

# 文字列から一行ずつ
CSV.parse(csv_text) do |row|
  p row
end
# => ["Ruby", "1995"]
#    ["Rust", "2010"]

# 文字列から一度に
p CSV.parse(csv_text)
# => [["Ruby", "1995"], ["Rust", "2010"]]

書き込み


require 'csv'

# ファイルへ書き込み
CSV.open("path/to/file.csv", "wb") do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

# 文字列へ書き込み
csv_string = CSV.generate do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

一行変換


require 'csv'

csv_string = ["CSV", "data"].to_csv   # => "CSV,data"
csv_array  = "CSV,String".parse_csv   # => ["CSV", "String"]

ショートカット


require 'csv'

CSV             { |csv_out| csv_out << %w{my data here} }  # to $stdout
CSV(csv = "")   { |csv_str| csv_str << %w{my data here} }  # to a String
CSV($stderr)    { |csv_err| csv_err << %w{my data here} }  # to $stderr

CSV と文字エンコーディング (M17n or Multilingualization)

This new CSV parser is m17n savvy. The parser works in the Encoding of the IO or String object being read from or written to. Your data is never transcoded (unless you ask Ruby to transcode it for you) and will literally be parsed in the Encoding it is in. Thus CSV will return Arrays or Rows of Strings in the Encoding of your data. This is accomplished by transcoding the parser itself into your Encoding.

Some transcoding must take place, of course, to accomplish this multiencoding support. For example, <tt>:col_sep</tt>, <tt>:row_sep</tt>, and <tt>:quote_char</tt> must be transcoded to match your data. Hopefully this makes the entire process feel transparent, since CSV's defaults should just magically work for you data. However, you can set these values manually in the target Encoding to avoid the translation.

It's also important to note that while all of CSV's core parser is now Encoding agnostic, some features are not. For example, the built-in converters will try to transcode data to UTF-8 before making conversions. Again, you can provide custom converters that are aware of your Encodings to avoid this translation. It's just too hard for me to support native conversions in all of Ruby's Encodings.

Anyway, the practical side of this is simple: make sure IO and String objects passed into CSV have the proper Encoding set and everything should just work. CSV methods that allow you to open IO objects (CSV::foreach(), CSV::open(), CSV::read(), and CSV::readlines()) do allow you to specify the Encoding.

One minor exception comes when generating CSV into a String with an Encoding that is not ASCII compatible. There's no existing data for CSV to use to prepare itself and thus you will probably need to manually specify the desired Encoding for most of those cases. It will try to guess using the fields in a row of output though, when using CSV::generate_line() or Array#to_csv().

特異メソッド

定義 説明
filter(options = Hash.new) {|row| ... }
filter(input, options = Hash.new) {|row| ... }
filter(input, output, options = Hash.new) {|row| ... }

このメソッドは CSV データに対して Unix のツール群のようなフィルタを構築するのに便利です。

foreach(path, options = Hash.new) {|row| ... } -> nil

このメソッドは CSV ファイルを読むための主要なインターフェイスです。各行が与えられたブロックに渡されます。

generate(str = "", options = Hash.new) {|csv| ... } -> String

このメソッドは与えられた文字列をラップして CSV のオブジェクトとしてブロックに渡します。ブロック内で CSV オブジェクトに行を追加することができます。ブロックを評価した結果は文字列を返します。

generate_line(row, options = Hash.new) -> String

このメソッドは一つの Array オブジェクトを CSV 文字列に変換するためのショートカットです。複数行のCSVを扱う際はCSV#<<を使うとより高速です。

instance(data = $stdout, options = Hash.new) -> CSV
instance(data = $stdout, options = Hash.new) {|csv| ... } -> object

このメソッドは CSV.new のように CSV のインスタンスを返します。しかし、返される値は Object#object_id と与えられたオプションをキーとしてキャッシュされます。

new(data, options = Hash.new) -> CSV

このメソッドは CSV ファイルを読み込んだり、書き出したりするために StringIO のインスタンスをラップします。

open(filename, mode = "rb", options = Hash.new) {|csv| ... } -> nil
open(filename, mode = "rb", options = Hash.new) -> CSV
open(filename, options = Hash.new) {|csv| ... } -> nil
open(filename, options = Hash.new) -> CSV

このメソッドは IO オブジェクトをオープンして CSV でラップします。これは CSV ファイルを書くための主要なインターフェイスとして使うことを意図しています。

parse(str, options = Hash.new) {|row| ... } -> nil
parse(str, options = Hash.new) -> Array

このメソッドは文字列を簡単にパースすることができます。ブロックを与えた場合は、ブロックにそれぞれの行を渡します。ブロックを省略した場合は、配列の配列を返します。

parse_line(line, options = Hash.new) -> Array

このメソッドは一行の CSV 文字列を配列に変換するためのショートカットです。

read(path, options = Hash.new) -> [Array] | CSV::Table
readlines(path, options = Hash.new) -> [Array] | CSV::Table

CSV ファイルを配列の配列にするために使います。 headers オプションに偽でない値を指定した場合は CSV::Table オブジェクトを返します。

table(path, options = Hash.new) -> CSV::Table | [Array]

以下と同等のことを行うメソッドです。

インスタンスメソッド

定義 説明
self << row -> self
add_row(row) -> self
puts(row) -> self

自身に row を追加します。

binmode -> self

IO#binmode に委譲します。

binmode? -> bool

IO#binmode? に委譲します。

close -> nil

IO#close に委譲します。

close_read -> nil

IO#close_read に委譲します。

close_write -> nil

IO#close_write に委譲します。

closed? -> bool

IO#closed? に委譲します。

col_sep -> String

カラム区切り文字列として使用する文字列を返します。

convert(name)
convert {|field| ... }
convert {|field, field_info| ... }

引数 name で指定した変換器かブロックに各フィールドを渡して文字列から別のオブジェクトへと変換します。

converters -> Array

現在の変換器のリストを返します。

each {|row| ... } -> nil

各行に対してブロックを評価します。

encoding -> Encoding

読み書きするときに使用するエンコーディングを返します。

eof -> bool
eof? -> bool

IO#eof, IO#eof? に委譲します。

external_encoding -> Encoding | nil

IO#external_encoding に委譲します。

fcntl(cmd, arg = 0) -> Integer

IO#fcntl に委譲します。

field_size_limit -> Integer

フィールドサイズの最大値を返します。

fileno -> Integer
to_i -> Integer

IO#fileno, IO#to_i に委譲します。

flock(operation) -> 0 | false

File#flock に委譲します。

flush -> self

IO#flush に委譲します。

force_quotes? -> bool

出力される全てのフィールドがクオートされる場合は、真を返します。

fsync -> 0 | nil

IO#fsync に委譲します。

shift -> Array | CSV::Row
gets -> Array | CSV::Row
readline -> Array | CSV::Row

StringIO をラップしたデータソースから一行だけ読み込んでフィールドの配列か CSV::Row のインスタンスを返します。

header_convert(name)
header_convert {|field| ... }
header_convert {|field, field_info| ... }

CSV#convert に似ていますが、ヘッダ行用のメソッドです。

header_converters -> Array

現在有効なヘッダ用変換器のリストを返します。

header_row? -> bool

次に読み込まれる行が、ヘッダである場合に真を返します。そうでない場合は、偽を返します。

headers -> Array | true | nil

nil を返した場合は、ヘッダは使用されません。真を返した場合は、ヘッダを使用するが、まだ読み込まれていません。配列を返した場合は、ヘッダは既に読み込まれています。

inspect -> String

ASCII 互換文字列で自身の情報を表したものを返します。

internal_encoding -> Encoding | nil

IO#internal_encoding に委譲します。

ioctl(cmd, arg = 0) -> Integer

IO#ioctl に委譲します。

isatty -> bool
tty? -> bool

IO#isatty, IO#tty? に委譲します。

lineno -> Integer

このファイルから読み込んだ最終行の行番号を返します。フィールドに含まれる改行はこの値には影響しません。

path -> String

IO#path に委譲します。

pid -> Integer | nil

IO#pid に委譲します。

pos -> Integer
tell -> Integer

IO#pos, IO#tell に委譲します。

pos=(n)

IO#pos= に委譲します。

quote_char -> String

フィールドをクオートするのに使用する文字列を返します。

read -> [Array] | CSV::Table
readlines -> [Array] | CSV::Table

残りの行を読み込んで配列の配列を返します。 self の生成時に headers オプションに偽でない値が指定されていた場合は CSV::Table オブジェクトを返します。

reopen(io) -> self

IO#reopen に委譲します。

return_headers? -> bool

ヘッダを返す場合は、真を返します。そうでない場合は、偽を返します。

rewind -> 0

IO#rewind に似ています。CSV#lineno を 0 にします。

row_sep -> String

行区切り文字列として使用する文字列を返します。

seek(offset, whence = IO::SEEK_SET) -> 0

IO#seek に委譲します。

skip_blanks? -> bool

真である場合は、空行を読み飛ばします。

stat -> File::Stat

IO#stat に委譲します。

string -> String

StringIO#string に委譲します。

sync -> bool

IO#sync に委譲します。

sync=(newstate)

IO#sync= に委譲します。

to_io -> self

IO#to_io に委譲します。

truncate(path, length) -> 0

File#truncate に委譲します。

unconverted_fields? -> bool

パースした結果が unconverted_fields というメソッドを持つ場合に真を返します。そうでない場合は、偽を返します。

write_headers? -> bool

ヘッダを出力先に書き込む場合は真を返します。そうでない場合は偽を返します。

定数

定義 説明
ConverterEncoding -> Encoding

すべての変換器で使用するエンコーディングです。

Converters -> Hash

このハッシュは名前でアクセスできる組み込みの変換器を保持しています。

DEFAULT_OPTIONS -> Hash

このオプションは呼び出し側で上書きしなかったときに使用するオプションです。

DateMatcher -> Regexp

日付 (Date) 形式のデータを発見したり変換したりするための正規表現です。

DateTimeMatcher -> Regexp

日時 (DateTime) 形式のデータを発見したり変換したりするための正規表現です。

HeaderConverters -> Hash

このハッシュは名前でアクセスできる組み込みのヘッダ用変換器を保存しています。

VERSION -> String

ライブラリのバージョンを表す文字列です。

継承したメソッド

! != __id__ __send__ instance_eval instance_exec method_missing singleton_method_added singleton_method_removed singleton_method_undefined all? any? chunk chunk_while collect collect_concat count cycle detect drop drop_while each_cons each_entry each_slice each_with_index each_with_object entries find_all find_index first grep grep_v group_by include? inject lazy max max_by min min_by minmax minmax_by none? one? partition reject reverse_each slice_after slice_before slice_when sort sort_by sum take take_while to_h to_set uniq zip def_delegator def_delegators delegate !~ <=> == === =~ _dump class clone define_singleton_method display enum_for eql? equal? extend freeze frozen? hash initialize initialize_copy instance_of? instance_variable_defined? instance_variable_get instance_variable_set instance_variables is_a? itself marshal_dump marshal_load method methods nil? object_id pretty_inspect pretty_print pretty_print_cycle pretty_print_inspect pretty_print_instance_variables private_methods protected_methods psych_to_yaml public_method public_methods public_send remove_instance_variable respond_to? respond_to_missing? send singleton_class singleton_method singleton_methods taint tainted? tap to_ary to_hash to_int to_proc to_regexp to_s to_str trust untaint untrust untrusted? .yaml_tag ::ARGF ::ARGV ::DATA ::ENV ::FALSE ::NIL ::RUBY_COPYRIGHT ::RUBY_DESCRIPTION ::RUBY_ENGINE ::RUBY_ENGINE_VERSION ::RUBY_PATCHLEVEL ::RUBY_PLATFORM ::RUBY_RELEASE_DATE ::RUBY_REVISION ::RUBY_VERSION ::SCRIPT_LINES__ ::STDERR ::STDIN ::STDOUT ::TOPLEVEL_BINDING ::TRUE