diff --git a/lib/csv.rb b/lib/csv.rb index 1635bda0..b7cb24de 100644 --- a/lib/csv.rb +++ b/lib/csv.rb @@ -1464,6 +1464,46 @@ def generate_line(row, **options) (new(str, **options) << row).string end + # :call-seq: + # CSV.generate_lines(rows) + # CSV.generate_lines(rows, **options) + # + # Returns the \String created by generating \CSV from + # using the specified +options+. + # + # Argument +rows+ must be an \Array of row. Row is \Array of \String or \CSV::Row. + # + # Special options: + # * Option :row_sep defaults to "\n" on Ruby 3.0 or later + # and $INPUT_RECORD_SEPARATOR ($/) otherwise.: + # $INPUT_RECORD_SEPARATOR # => "\n" + # * This method accepts an additional option, :encoding, which sets the base + # Encoding for the output. This method will try to guess your Encoding from + # the first non-+nil+ field in +row+, if possible, but you may need to use + # this parameter as a backup plan. + # + # For other +options+, + # see {Options for Generating}[#class-CSV-label-Options+for+Generating]. + # + # --- + # + # Returns the \String generated from an + # CSV.generate_lines(['foo', '0'], ['bar', '1'], ['baz', '2']) # => "foo,0\nbar,1\nbaz.2\n" + # + # --- + # + # Raises an exception + # # Raises NoMethodError (undefined method `find' for :foo:Symbol) + # CSV.generate_lines(:foo) + # + def generate_lines(rows, **options) + self.generate(**options) do |csv| + rows.each do |row| + csv << row + end + end + end + # # :call-seq: # open(file_path, mode = "rb", **options ) -> new_csv diff --git a/test/csv/interface/test_write.rb b/test/csv/interface/test_write.rb index 02c2c5c5..0cd39a76 100644 --- a/test/csv/interface/test_write.rb +++ b/test/csv/interface/test_write.rb @@ -85,6 +85,15 @@ def test_generate_line_shortcut LINE end + def test_generate_lines + lines = CSV.generate_lines([["foo", "bar"], [1, 2], [3, 4]]) + assert_equal(<<-LINES, lines) +foo,bar +1,2 +3,4 + LINES + end + def test_headers_detection headers = ["a", "b", "c"] CSV.open(@output.path, "w", headers: true) do |csv|