End of Life Ruby 3.2 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| ... }
lib/csv.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.2.0/lib/csv.rb, line 1005
def instance(data = $stdout, **options)
# create a _signature_ for this method call, data object and options
sig = [data.object_id] +
options.values_at(*DEFAULT_OPTIONS.keys)
# fetch or create the instance for this signature
@@instances ||= Hash.new
instance = (@@instances[sig] ||= new(data, **options))
if block_given?
yield instance # run block, if given, returning result
else
instance # or return the instance
end
end
Creates or retrieves cached CSV objects. For arguments and options, see CSV.new.
This API is not Ractor-safe.
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