hex = 0x0905 => 2309 2.1.2 :017 > b-6ren">
gpt4 book ai didi

尝试动态创建 unicode 字符串的 Ruby 抛出 "invalid Unicode escape"错误

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

我有一个要求,我想使用插值动态创建一个 unicode 字符串。例如请看下面在 irb 中试过的代码

2.1.2 :016 > hex = 0x0905
=> 2309
2.1.2 :017 > b = "\u#{hex}"
SyntaxError: (irb):17: invalid Unicode escape
b = "\u#{hex}"

十六进制代码 0x0905 对应梵文字母 A 的独立元音 unicode。

我不知道如何达到预期的结果。

最佳答案

您可以将编码传递给 Integer#chr :

hex = 0x0905
hex.chr('UTF-8') #=> "अ"

参数可以省略,如Encoding::default_internal设置为 UTF-8:

$ ruby -E UTF-8:UTF-8 -e "p 0x0905.chr"
"अ"

您还可以将代码点附加到其他字符串:

'' << hex #=> "अ"

关于尝试动态创建 unicode 字符串的 Ruby 抛出 "invalid Unicode escape"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27124145/

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