diff --git a/lib/csv.rb b/lib/csv.rb index e5ecf5c..7d77079 100644 --- a/lib/csv.rb +++ b/lib/csv.rb @@ -1502,6 +1502,7 @@ class CSV when /\A[^:]+/; Encoding.find($&) end ) || Encoding.default_internal || Encoding.default_external + @force_encoding = !!options.delete(:force_encoding) # # prepare for building safe regular expressions in the target encoding, # if we can transcode the needed characters @@ -1605,6 +1606,11 @@ class CSV attr_reader :encoding # + # The flag to encode inserted strings forcibly. + # + attr_reader :force_encoding + + # # The line number of the last row read from this file. Fields with nested # line-end characters will not affect this count. # @@ -1656,10 +1662,13 @@ class CSV output = row.map(&@quote).join(@col_sep) + @row_sep # quote and separate if @io.is_a?(StringIO) and - output.encoding != raw_encoding and - (compatible_encoding = Encoding.compatible?(@io.string, output)) - @io.set_encoding(compatible_encoding) - @io.seek(0, IO::SEEK_END) + output.encoding != raw_encoding + if force_encoding + output = output.force_encoding(raw_encoding) + elsif compatible_encoding = Encoding.compatible?(@io.string, output) + @io.set_encoding(compatible_encoding) + @io.seek(0, IO::SEEK_END) + end end @io << output