the question is that the title say! who can tell me how do this in ruby!
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