Ruby 中的百分比编码

Percent encoding in Ruby

在Ruby中,我通过

获得'ä'的百分比编码
require 'cgi'
CGI.escape('ä')
=> "%C3%A4"

'ä'.unpack('H2' * 'ä'.bytesize)
=> ["c3", "a4"]

我有两个问题:

  1. 第一个运算的逆向是什么?不应该

    ["c3", "a4"].pack('H2' * 'ä'.bytesize)
    => "\xC3\xA4"
    
  2. 对于我的应用程序,我需要将 'ä' 编码为“%E4”,这是 'ä'.ord 的十六进制值。有什么Ruby方法吗?

正如我在评论中提到的,将字符 ä 等同于代码点 228 (0xE4) 意味着您正在处理 ISO 8859-1 character encoding.

所以,您需要告诉 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"