CGI.unescape 和 URI.decode_www_form_component 有什么区别?

What's the difference between CGI.unescape and URI.decode_www_form_component?

这些函数似乎做同样的事情。

irb> CGI.unescape "Sloths%3A+Society+and+Habitat"
=> "Sloths: Society and Habitat"

irb> URI.decode_www_form_component "Sloths%3A+Society+and+Habitat"
=> "Sloths: Society and Habitat"

有什么区别?

这些方法非常相似。它们都接受一个字符串和一个编码,并且 return 一个指定编码的字符串,% 转义解码。但还是有区别的:

无效转义

如果字符串包含无效的转义序列,

URI.decode_www_form_component 引发 ArgumentError

URI.decode_www_form_component('%xz')
# ArgumentError: invalid %-encoding (%xz)

CGI.unescape 直接忽略它们。

CGI.unescape('%xz')
# "%xz"

无效编码

CGI.unescape 如果结果无效则忽略您指定的编码

p CGI.unescape("\u263a", 'ASCII')
# "☺"

URI.decode_www_form_component不关心

p URI.decode_www_form_component("\u263a", 'ASCII')
# "\xE2\x98\xBA"

最后(我什至不愿提及这一点),URI.decode_www_form_component 稍微 更快,因为它使用预先计算的哈希来解码所有 485 个有效的转义码(它是大小写-sensitive),而 CGI.unescape 实际上解释十六进制代码并将其重新打包为字符。