Force strings to UTF-8 from any encoding

前端 未结 4 1359
不知归路
不知归路 2020-12-13 13:36

In my rails app I\'m working with RSS feeds from all around the world, and some feeds have links that are not in UTF-8. The original feed links are out of my control, and i

4条回答
  •  天命终不由人
    2020-12-13 14:10

    Ruby 1.9

    "Forcing" an encoding is easy, however it won't convert the characters just change the encoding:

    str = str.force_encoding('UTF-8')
    
    str.encoding.name # => 'UTF-8'
    

    If you want to perform a conversion, use encode:

    begin
      str.encode("UTF-8")
    rescue Encoding::UndefinedConversionError
      # ...
    end
    

    I would definitely read the following post for more information:
    http://graysoftinc.com/character-encodings/ruby-19s-string

提交回复
热议问题