Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

CSV.instance

instance(string, **options)
instance(io = $stdout, **options)
instance(string, **options) {|csv| ... }
instance(io = $stdout, **options) {|csv| ... }

Creates or retrieves cached CSV objects. For arguments and options, see CSV.new.


With no block given, returns a CSV object.

The first call to instance creates and caches a CSV object:

Example
s0 = 's0'
csv0 = CSV.instance(s0)
csv0.class # => CSV

Subsequent calls to instance with that same string or io retrieve that same cached object:

Example
csv1 = CSV.instance(s0)
csv1.class # => CSV
csv1.equal?(csv0) # => true # Same CSV object

A subsequent call to instance with a different string or io creates and caches a different CSV object.

Example
s1 = 's1'
csv2 = CSV.instance(s1)
csv2.equal?(csv0) # => false # Different CSV object

All the cached objects remains available:

Example
csv3 = CSV.instance(s0)
csv3.equal?(csv0) # true # Same CSV object
csv4 = CSV.instance(s1)
csv4.equal?(csv2) # true # Same CSV object

When a block is given, calls the block with the created or retrieved CSV object; returns the block’s return value:

Example
CSV.instance(s0) {|csv| :foo } # => :foo
See also .generate_line .new .generate .open also in 3.3 · 3.2 · 3.1