Project

General

Profile

Actions

Bug #15521

closed

encoding is missed when using `CSV.generate`

Added by sue445 (Go Sueyoshi) over 5 years ago. Updated over 5 years ago.

Status:
Closed
Target version:
-
ruby -v:
ruby 2.6.0p0
[ruby-dev:50755]

Description

Sample code

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

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...

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0