【发布时间】:2013-08-16 14:47:23
【问题描述】:
我在生产中的某个地方有一个文件,我没有可以访问该文件,当由 ruby 脚本加载时,针对内容的正则表达式失败并显示 ArgumentError => invalid byte sequence in UTF-8。
我相信我已经根据此处所有要点的答案进行了修复:ruby 1.9: invalid byte sequence in UTF-8
# Remove all invalid and undefined characters in the given string
# (ruby 1.9.3)
def safe_str str
# edited based on matt's comment (thanks matt)
s = str.encode('utf-16', 'utf-8', invalid: :replace, undef: :replace, replace: '')
s.encode!('utf-8', 'utf-16')
end
但是,我现在想构建我的 rspec 以验证代码是否有效。我无权访问导致问题的文件,因此我想以编程方式创建一个编码错误的字符串。
我尝试过以下变化:
bad_str = (100..1000).to_a.inject('') {|s,c| s << c; s}
bad_str.length.should > safe_str(bad_str).length
或者,
bad_str = (100..1000).to_a.pack(c*)
bad_str.length.should > safe_str(bad_str).length
但长度始终相同。我也尝试过不同的字符范围;并不总是 100 到 1000。
关于如何在 ruby 1.9.3 脚本中使用无效编码构建字符串的任何建议?
【问题讨论】:
-
你的坏字符串会触发原来的“无效字节序列”异常吗?也许他们真的很糟糕,但
safe_str出于某种原因没有抓住它。 -
谢谢@HewWolff 我还没有部署它。我想让我的测试正常运行(根据下面的 matt 评论,这是一件好事)。