Ruby 2.5.0 リファレンスマニュアル > ライブラリ一覧 > csvライブラリ > 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
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().
定義 | 説明 | |
---|---|---|
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?
yield_self
.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