Issue #15521 has been reported by sue445 (Go Sueyoshi).

----------------------------------------
Bug #15521: encoding is missed when using `CSV.generate`
https://bugs.ruby-lang.org/issues/15521

* Author: sue445 (Go Sueyoshi)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
* ruby -v: ruby 2.6.0p0
* Backport: 2.4: UNKNOWN, 2.5: UNKNOWN, 2.6: UNKNOWN
----------------------------------------
# Sample code
~~~ ruby
require "csv"

rows = [
  ["a", "b", "c", "d", "e"],
  ["あ", "い", "う", "え", "お"],
]

str = CSV.generate do |csv|
  rows.each do |row|
    csv << row
  end
end

p str
p str.encoding
~~~


# Expected (on Ruby 2.5.3)
~~~
$ ruby csv_generate.rb
"a,b,c,d,e\nあ,い,う,え,お\n"
#<Encoding:UTF-8>
~~~

# Actual (on Ruby 2.6.0)
~~~
$ ruby csv_generate.rb
"a,b,c,d,e\n\xE3\x81\x82,\xE3\x81\x84,\xE3\x81\x86,\xE3\x81\x88,\xE3\x81\x8A\n"
#<Encoding:ASCII-8BIT>
~~~


This behavior is same to ruby-trunk

~~~
$ ruby -v
ruby 2.7.0dev (2019-01-10 trunk 66768) [x86_64-darwin17]
~~~

# Workaround
Use `force_encoding`

~~~ruby
require "csv"

rows = [
  ["a", "b", "c", "d", "e"],
  ["あ", "い", "う", "え", "お"],
]

str = CSV.generate do |csv|
  rows.each do |row|
    csv << row
  end
end.force_encoding("UTf-8")

p str
p str.encoding
~~~

This works, but little dirty...



-- 
https://bugs.ruby-lang.org/