开发者

How can i transform the utf8 chars to iso8859-1

开发者 https://www.devze.com 2022-12-28 19:09 出处:网络
the question is that开发者_StackOverflow中文版 the title say! who can tell me how do this in ruby!~ UPDATE ~

the question is that开发者_StackOverflow中文版 the title say! who can tell me how do this in ruby!


~ UPDATE ~

ruby-iconv has been superseded from Ruby 1.9.3 onwards by the encode method. See Jörg W Mittag's answer for details, but in short:

utf8string = "èàòppè"
iso_string = utf8string.encode('ISO-8859-1')

I agree with Williham Totlandt in thinking that this type of conversion might not be the smartest idea ever, but anyway: use ruby-iconv :)

utf8string = "èàòppè"
iso_string = Iconv.conv 'iso8859-1', 'UTF-8', utf8string 


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   # => #<Encoding:UTF-8>
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   # => #<Encoding:ISO8859-1>
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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号