End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
CSV.generate
# File tmp/rubies/ruby-3.0.5/lib/csv.rb, line 1269
def generate(str=nil, **options)
encoding = options[:encoding]
# add a default empty String, if none was given
if str
str = StringIO.new(str)
str.seek(0, IO::SEEK_END)
str.set_encoding(encoding) if encoding
else
str = +""
str.force_encoding(encoding) if encoding
end
csv = new(str, **options) # wrap
yield csv # yield for appending
csv.string # return final String
end
-
Argument
csv_string, if given, must be a String object; defaults to a new empty String. -
Arguments
options, if given, should be generating options. See Options for Generating.
Creates a new CSV object via CSV.new(csv_string, **options); calls the block with the CSV object, which the block may modify; returns the String generated from the CSV object.
Note that a passed String is modified by this method. Pass csv_string.dup if the String must be preserved.
This method has one additional option: :encoding, which sets the base Encoding for the output if no no str is specified. CSV needs this hint if you plan to output non-ASCII compatible data.
Add lines:
input_string = "foo,0\nbar,1\nbaz,2\n" output_string = CSV.generate(input_string) do |csv| csv << ['bat', 3] csv << ['bam', 4] end output_string # => "foo,0\nbar,1\nbaz,2\nbat,3\nbam,4\n" input_string # => "foo,0\nbar,1\nbaz,2\nbat,3\nbam,4\n" output_string.equal?(input_string) # => true # Same string, modified
Add lines into new string, preserving old string:
input_string = "foo,0\nbar,1\nbaz,2\n" output_string = CSV.generate(input_string.dup) do |csv| csv << ['bat', 3] csv << ['bam', 4] end output_string # => "foo,0\nbar,1\nbaz,2\nbat,3\nbam,4\n" input_string # => "foo,0\nbar,1\nbaz,2\n" output_string.equal?(input_string) # => false # Different strings
Create lines from nothing:
output_string = CSV.generate do |csv| csv << ['foo', 0] csv << ['bar', 1] csv << ['baz', 2] end output_string # => "foo,0\nbar,1\nbaz,2\n"
Raises an exception if csv_string is not a String object:
# Raises TypeError (no implicit conversion of Integer into String) CSV.generate(0)