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

class CSV

クラスの継承リスト: CSV < Enumerable < Object < Kernel < BasicObject
extend: Forwardable

要約

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

読み込み

# ファイルから一行ずつ
CSV.foreach("path/to/file.csv") do |row|
  # use row here...
end

# ファイルから一度に
arr_of_arrs = CSV.read("path/to/file.csv")

# 文字列から一行ずつ
CSV.parse("CSV,data,String") do |row|
  # use row here...
end

# 文字列から一行ずつ
arr_of_arrs = CSV.parse("CSV,data,String")

書き込み

# ファイルへ書き込み
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

一行変換

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

ショートカット

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().

I try to point out any other Encoding issues in the documentation of methods as they come up.

This has been tested to the best of my ability with all non-"dummy" Encodings Ruby ships with. However, it is brave new code and may have some bugs. Please feel free to {report}[mailto:james@grayproductions.net] any issues you find with it.

特異メソッド

定義 説明
dump(ary_of_objs, io = "", options = Hash.new) -> String | nil

このメソッドは Ruby オブジェクトの配列を文字列や CSV ファイルにシリアライズすることができます。 Marshalyaml よりは不便ですが、スプレッドシートやデータベース とのやりとりには役に立つでしょう。

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 文字列に変換するためのショートカットです。

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

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

load(io_or_str, options = Hash.new) -> Array

このメソッドは CSV.dump で出力されたデータを読み込みます。

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]
readlines(path, options = Hash.new) -> [Array]

CSV ファイルを配列の配列にするために使います。

table(path, options = Hash.new) -> Array

以下の例と同等のことを行うメソッドです。 日本語の CSV ファイルを扱う場合はあまり使いません。

インスタンスメソッド

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

自身に row を追加します。

binmode

delegate

binmode?

delegate

close

delegate

close_read

delegate

close_write

delegate

closed?

delegate

col_sep -> String

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

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

You can use this method to install a CSV::Converters built-in, or provide a block that handles a custom conversion.

converters -> Array

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

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

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

encoding -> Encoding

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

eof

delegate

eof?

delegate

external_encoding

delegate

fcntl

delegate

field_size_limit -> Fixnum

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

fileno

delegate

flock

delegate

flush

delegate

force_quotes? -> bool

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

fsync

delegate

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| ... }

Identical to CSV#convert(), but for header rows.

header_converters -> Array

Returns the current list of converters in effect for headers. See CSV::new for details. Built-in converters will be returned by name, while others will be returned as is.

header_row? -> bool

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

headers -> Array | true | nil

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

inspect -> String

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

internal_encoding

delegate

ioctl

delegate

isatty

delegate

lineno -> Fixnum

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

path

delegate

pid

delegate

pos

delegate

pos=

delegate

quote_char -> String

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

read -> [Array]
readlines -> [Array]

残りの行を読み込んで配列の配列を返します。

reopen

delegate

return_headers? -> bool

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

rewind -> 0

Rewinds the underlying IO object and resets CSV's lineno() counter.

row_sep -> String

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

seek

delegate

skip_blanks? -> bool

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

stat

delegate

string

delegate

sync

delegate

sync=

delegate

tell

delegate

to_i

delegate

to_io

delegate

truncate

delegate

tty?

delegate

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

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

継承したメソッド

! != all? any? chunk 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 group_by include? inject max max_by min min_by minmax minmax_by none? one? partition reject reverse_each slice_before sort sort_by take take_while to_set zip def_delegator def_delegators == === =~ __id__ __send__ _dump class clone dclone display enum_for eql? equal? extend freeze frozen? hash initialize initialize_copy instance_eval instance_exec instance_of? instance_variable_defined? instance_variable_get instance_variable_set instance_variables is_a? marshal_dump marshal_load method method_missing methods must_be must_be_close_to must_be_empty must_be_instance_of must_be_kind_of must_be_nil must_be_same_as must_be_within_epsilon must_equal must_include must_match must_raise must_respond_to must_send must_throw nil? pretty_inspect pretty_print pretty_print_cycle pretty_print_inspect pretty_print_instance_variables private_methods protected_methods public_methods remove_instance_variable respond_to? respond_to_missing? singleton_class singleton_method_added singleton_method_removed singleton_method_undefined singleton_methods taint tainted? tap to_ary to_hash to_int to_proc to_regexp to_s to_str to_yaml to_yaml_properties to_yaml_style trust untaint untrust untrusted? wont_be wont_be_close_to wont_be_empty wont_be_instance_of wont_be_kind_of wont_be_nil wont_be_same_as wont_be_within_epsilon wont_equal wont_include wont_match wont_respond_to