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