Ruby invalid byte sequence in UTF-8 (ArgumentError)解决办法

  • A+
所属分类:ruby 技巧

Ruby invalid byte sequence in UTF-8 (ArgumentError)解决办法

有时候因为编码问题出现如下错误提示:

Uncaught exception: invalid byte sequence in UTF-8
    e:/myCode/ruby/22/myTest.rb:21:in `block (2 levels) in <top (required)>'
    e:/myCode/ruby/22/myTest.rb:19:in `each_line'
    e:/myCode/ruby/22/myTest.rb:19:in `block in <top (required)>'
    e:/myCode/ruby/22/myTest.rb:17:in `open'
    e:/myCode/ruby/22/myTest.rb:17:in `<top (required)>'
    C:/Ruby24-x64/bin/rdebug-ide:23:in `load'
    C:/Ruby24-x64/bin/rdebug-ide:23:in `<main>'
e:/myCode/ruby/22/myTest.rb:21:in `block (2 levels) in <top (required)>': invalid byte sequence in UTF-8 (ArgumentError)

解决办法

调用对应对象encode方法如下即可。

line.encode!('UTF-8', 'UTF-8', :invalid => :replace)
百分购

发表评论

您必须才能发表评论!