Ruby 相当于 PHPs urlencode

Ruby equivalent to PHPs urlencode

我需要转换 Ruby 中包含字符“ö”的 URL。

在 PHP 中,url编码 returns %F6 for ö 这似乎是 ISO 8859 中“ö”的十六进制值。

我尝试了几种不同的方法,但其中 none 返回了正确的字符:

我应该使用什么方法来获得所需的输出?

-e-

附加要求:

我只需要转换url路径中的这些字符。冒号、斜杠等应保持不变:

http://example.com/this/is/an/ö

将会

http://example.com/this/is/an/%F6

我找到了解决方案

converter = Encoding::Converter.new("utf-8", "iso-8859-1")
CGI.escape(converter.convert('ö'))

=> "%F6"

Ruby 默认使用 UTF-8 字符串:

str = 'ö'

str.encoding
#=> #<Encoding:UTF-8>

如果你想要 Ruby 中的 ISO 8859 编码字符串,你必须转换它:

str.encode('ISO-8859-1')
#=> "\xF6"

到URL-encode一个字符串,有CGI.escape:

require 'cgi'

CGI.escape(str.encode('ISO-8859-1'))
#=> "%F6"

编码 URL,使用 URI.escape:

require 'uri'

url = 'http://example.com/this/is/an/ö'
URI.escape(url.encode('ISO-8859-1'))
#=> "http://example.com/this/is/an/%F6"