Method: CSV::Table#to_csv
- Defined in:
- lib/csv/table.rb
#to_csv(write_headers: true, limit: nil, **options) ⇒ Object Also known as: to_s
:call-seq:
table.to_csv(**options) -> csv_string
Returns the table as CSV string. See Options for Generating.
Defaults option write_headers to true:
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):
table.to_csv(write_headers: false) # => "foo,0\nbar,1\nbaz,2\n"
Limit rows if option limit is given like 2:
table.to_csv(limit: 2) # => "Name,Value\nfoo,0\nbar,1\n"
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 |
# File 'lib/csv/table.rb', line 1004 def to_csv(write_headers: true, limit: nil, **) array = write_headers ? [headers.to_csv(**)] : [] 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(**)) unless row.header_row? end array.join("") end |