红宝石 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 字符?
谢谢!