Skip to content

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

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"
See also #to_a #to_s #push #values_at also in 3.3 · 3.1 · 3.0