StringIO的Ruby CSV BOM | UTF-8编码

问题描述 投票:2回答:1

Ruby 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

显然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

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

谢谢!

ruby csv utf-8 byte-order-mark ruby-csv
1个回答
0
投票
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

© www.soinside.com 2019 - 2024. All rights reserved.