End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
CSV::Table#to_csv
table.to_csv(**options) → csv_string
lib/csv/table.rb
View on GitHub ↗
# File tmp/rubies/ruby-3.2.0/lib/csv/table.rb, line 1004
def to_csv(write_headers: true, limit: nil, **options)
array = write_headers ? [headers.to_csv(**options)] : []
limit ||= @table.size
limit = @table.size + 1 + limit if limit < 0
limit = 0 if limit < 0
@table.first(limit).each do |row|
array.push(row.fields.to_csv(**options)) unless row.header_row?
end
array.join("")
end
Returns the table as CSV string. See Options for Generating.
Defaults option write_headers to true:
Example
source = "Name,Value\nfoo,0\nbar,1\nbaz,2\n" table = CSV.parse(source, headers: true) table.to_csv # => "Name,Value\nfoo,0\nbar,1\nbaz,2\n"
Omits the headers if option write_headers is given as false (see Option write_headers):
Example
table.to_csv(write_headers: false) # => "foo,0\nbar,1\nbaz,2\n"
Limit rows if option limit is given like 2:
Example
table.to_csv(limit: 2) # => "Name,Value\nfoo,0\nbar,1\n"