UTF-8中的字节序列无效(ArgumentError)

我正在尝试运行Ruby脚本,并且总是在这一行上出错:

file_content.gsub(/dr/i,'med') 

我试图用“med”代替“dr”。

错误是:

 program.rb:4:in `gsub': invalid byte sequence in UTF-8 (ArgumentError) 

为什么,我该如何解决这个问题呢?

我正在使用Ruby 2.2.1p85开发MAC OS X Yosemite机器。

可能你的字符串不是UTF-8格式,所以请使用

 if ! file_content.valid_encoding? s = file_content.encode("UTF-16be", :invalid=>:replace, :replace=>"?").encode('UTF-8') s.gsub(/dr/i,'med') end 

请参阅“ Ruby 2.0.0 String#Match ArgumentError:UTF-8中的无效字节序列 ”。