Ruby `split': invalid byte sequence in UTF-8 (ArgumentError)

后端 未结 2 1557
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-12 10:04

I am trying to populate the movie object, but when parsing through the u.item file I get this error:

`split\': invalid byte sequence in UTF-8

2条回答
  •  时光取名叫无心
    2021-02-12 10:23

    Ruby is somewhat sensitive to character encoding issues. You can do a number of things that might solve your problem. For example:

    1. Put an encoding comment at the top of your source file.

      # encoding: utf-8
      
    2. Explicitly encode your line before splitting.

      line = line.encode('UTF-8').split("|")
      
    3. Replace invalid characters, instead of raising an Encoding::InvalidByteSequenceError exception.

      line.encode('UTF-8', :invalid => :replace).split("|")
      

    Give these suggestions a shot, and update your question if none of them work for you. Hope it helps!

提交回复
热议问题