How can i transform the utf8 chars to iso8859-1

前端 未结 2 842
日久生厌
日久生厌 2021-01-16 07:11

the question is that the title say! who can tell me how do this in ruby!

2条回答
  •  耶瑟儿~
    2021-01-16 07:36

    With Ruby 1.9, that's particularly easy, because all strings carry their encoding with them:

    # coding: UTF-8
    
    u = 'µ'
    

    As you can see, the string is encoded as UTF-8:

    p u.encoding   # => #
    p u.bytes.to_a # => [194, 181]
    

    Transcoding the string is quite easy:

    i = u.encode('ISO-8859-1')
    

    i is now in ISO-8859-1 encoding:

    p i.encoding   # => #
    p i.bytes.to_a # => [181]
    

    If you want to write to a file, the network, an IO stream or the console, it gets even easier. In Ruby 1.9, those objects are tagged with an encoding just like strings are, and transcoding happens automatically. Just say print or puts and Ruby will do the transcoding for you:

    File.open('test.txt', 'w', encoding: 'ISO-8859-1') do |f|
      f.puts u
    end
    

提交回复
热议问题