StringIO 的 Ruby CSV BOM|UTF-8 编码

jov*_*pcg 6 ruby csv byte-order-mark utf-8 ruby-csv

红宝石 2.6.3。

我一直在尝试将StringIO对象解析为CSV具有bom|utf-8编码的实例,以便去除 BOM 字符(不需要的)并将内容编码为 UTF-8:

require 'csv'

CSV_READ_OPTIONS = { headers: true, encoding: 'bom|utf-8' }.freeze

content = StringIO.new("\xEF\xBB\xBFid\n123")
first_row = CSV.parse(content, CSV_READ_OPTIONS).first

first_row.headers.first.include?("\xEF\xBB\xBF")     # This returns true
Run Code Online (Sandbox Code Playgroud)

显然bom|utf-8编码不适用于StringIO对象,但我发现它适用于文件,例如:

require 'csv'

CSV_READ_OPTIONS = { headers: true, encoding: 'bom|utf-8' }.freeze

# File content is: "\xEF\xBB\xBFid\n12"
first_row = CSV.read('bom_content.csv', CSV_READ_OPTIONS).first

first_row.headers.first.include?("\xEF\xBB\xBF")     # This returns false
Run Code Online (Sandbox Code Playgroud)

考虑到我需要StringIO直接使用,为什么CSV忽略bom|utf-8编码?有没有办法从StringIO实例中删除 BOM 字符?

谢谢!

3li*_*t0r 6

Ruby 2.7 添加了该set_encoding_by_bom方法到IO. 此方法使用字节顺序标记并设置编码。

require 'csv'
require 'stringio'

CSV_READ_OPTIONS = { headers: true }.freeze

content = StringIO.new("\xEF\xBB\xBFid\n123")
content.set_encoding_by_bom

first_row = CSV.parse(content, CSV_READ_OPTIONS).first
first_row.headers.first.include?("\xEF\xBB\xBF")
#=> false
Run Code Online (Sandbox Code Playgroud)


Max*_*Max 2

Ruby 不喜欢 BOM。它只在读取文件时处理它们,而不会在其他任何地方处理它们,即使这样它也只是读取它们以便可以删除它们。如果您想要字符串的 BOM,或者写入文件时的 BOM,则必须手动处理。

可能有一些宝石可以做到这一点,尽管自己做很容易

if string[0...3] == "\xef\xbb\xbf"
  string = string[3..-1].force_encoding('UTF-8')
elsif string[0...2] == "\xff\xfe"
  string = string[2..-1].force_encoding('UTF-16LE')
# etc
Run Code Online (Sandbox Code Playgroud)