文件编码与红宝石

时间:2010-05-28 12:17:49

标签: ruby file-encodings

我在文件编码方面遇到了一些问题。

我收到一个网址编码的字符串,例如“sometext%C3%B3 + more +%26 + andmore”,unescape它,处理数据,并用windows-1252编码保存。

转换是这些:

irb(main) >> value
=> "sometext%C3%B3+more+%26+andmore"
irb(main) >> CGI::unescape(value)
=> "sometext\303\263 more & andmore"
irb(main) >> #Some code and saved into a file using open(filename, "w:WINDOWS-1252")
irb(main) >> # result in the file:
=> sometextĂ³ more & andmore

结果应为sometextó more & andmore

1 个答案:

答案 0 :(得分:4)

Ruby 1.9中添加了编码支持,因此以下代码来自Ruby 1.9.1:

require 'cgi'
#=> true
s = "sometext%C3%B3+more+%26+andmore"
#=> "sometext%C3%B3+more+%26+andmore"
t = CGI::unescape s
#=> "sometext\xC3\xB3 more & andmore"
t.force_encoding 'utf-8' # telling Ruby that the string is UTF-8 encoded
#=> "sometextó more & andmore"
t.encode! 'windows-1252' # changing encoding to windows-1252
#=> "sometext? more & andmore"
# here you do whatever you want to do with windows-1252 encoded string

Here你有很多关于Ruby和编码的信息。

PS。 Ruby 1.8.7没有对编码的内置支持,因此您必须使用一些外部库进行转换,例如iconv

require 'iconv'
#=> true
require 'cgi'
#=> true
s = "sometext%C3%B3+more+%26+andmore"
#=> "sometext%C3%B3+more+%26+andmore"
t = CGI::unescape s
#=> "sometext\303\263 more & andmore"
Iconv.conv 'windows-1252', 'utf-8', t
#=> "sometext\363 more & andmore"
# \363 is ó in windows-1252 encoding