Ruby 1.9.2 リファレンスマニュアル > ライブラリ一覧 > csvライブラリ > 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
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.
定義 | 説明 | |
---|---|---|
self << row -> self
|
自身に row を追加します。 |
|
binmode
|
delegate |
|
binmode?
|
delegate |
|
close
|
delegate |
|
close_read
|
delegate |
|
close_write
|
delegate |
|
closed?
|
delegate |
|
col_sep -> String
|
カラム区切り文字列として使用する文字列を返します。 |
|
convert(name)
|
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
|
String や IO をラップしたデータソースから一行だけ読み込んで フィールドの配列か CSV::Row のインスタンスを返します。 |
|
header_convert(name)
|
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]
|
残りの行を読み込んで配列の配列を返します。 |
|
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