Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
CSV.generate_line
# File tmp/rubies/ruby-3.3.0/lib/csv.rb, line 1446
def generate_line(row, **options)
options = {row_sep: InputRecordSeparator.value}.merge(options)
str = +""
if options[:encoding]
str.force_encoding(options[:encoding])
else
fallback_encoding = nil
output_encoding = nil
row.each do |field|
next unless field.is_a?(String)
fallback_encoding ||= field.encoding
next if field.ascii_only?
output_encoding = field.encoding
break
end
output_encoding ||= fallback_encoding
if output_encoding
str.force_encoding(output_encoding)
end
end
(new(str, **options) << row).string
end
Returns the String created by generating CSV from ary using the specified options.
Argument ary must be an Array.
Special options:
-
Option
:row_sepdefaults to"\n"> on Ruby 3.0 or later and <tt>$INPUT_RECORD_SEPARATOR($/) otherwise.:Example$INPUT_RECORD_SEPARATOR # => "\n"
-
This method accepts an additional option,
:encoding, which sets the baseEncodingfor the output. This method will try to guess yourEncodingfrom the first non-nilfield inrow, if possible, but you may need to use this parameter as a backup plan.
For other options, see Options for Generating.
Returns the String generated from an Array:
CSV.generate_line(['foo', '0']) # => "foo,0\n"
Raises an exception if ary is not an Array:
# Raises NoMethodError (undefined method `find' for :foo:Symbol) CSV.generate_line(:foo)