gpt4 book ai didi

ruby - Ruby 中的百分比编码

转载 作者:数据小太阳 更新时间:2023-10-29 07:33:47 24 4
gpt4 key购买 nike

在 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"

关于ruby - Ruby 中的百分比编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31318182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com