正如我在评论中提到的,将字符 ä 等同于代码点 228 (0xE4) 意味着您正在处理ISO 8859-1 字符编码。
所以,你需要告诉 Ruby 你想要对你的字符串使用什么编码。
str1 = "Hullo ängstrom" # uses whatever encoding is current, generally utf-8
str2 = str1.encode('iso-8859-1')
然后,您可以根据需要对其进行编码:
require 'cgi'
s2c = CGI.escape str2
#=> "Hullo+%E4ngstrom"
require 'uri'
s2u = URI.escape str2
#=> "Hullo%20%E4ngstrom"
然后,要反转它,您必须首先 (a) 取消转义值,然后 (b) 将编码转换回您习惯的编码(可能是 UTF-8),告诉 Ruby 它应该将代码点解释为什么字符编码:
s3a = CGI.unescape(s2c) #=> "Hullo \xE4ngstrom"
puts s3a.encode('utf-8','iso-8859-1')
#=> "Hullo ängstrom"
s3b = URI.unescape(s2u) #=> "Hullo \xE4ngstrom"
puts s3b.encode('utf-8','iso-8859-1')
#=> "Hullo ängstrom"