Ruby将UTF-8字符串编码为UTF-16

时间:2014-01-01 07:03:45

标签: ruby encoding utf-8 character-encoding utf-16

我想将UTF-16编码存储为另一个变量UTF-8字符串。

1.9.3p194 :117 > str = "سلام"
 => "سلام" 
1.9.3p194 :118 > enc = str.encode("utf-16")
 => "\uFEFF\u0633\u0644\u0627\u0645" 
1.9.3p194 :119 > puts enc
??3D'E
 => nil 

我想将\uFEFF\u0633\u0644\u0627\u0645(不是??3D'E)存储到UTF-8字符串中,以便能够将其与其他UTF-8字符串连接

1 个答案:

答案 0 :(得分:2)

使用String#inspect

str = "سلام"
# => "سلام"
enc = str.encode("utf-16")
# => "\uFEFF\u0633\u0644\u0627\u0645"
puts enc
# output: ▒▒3D'E
# => nil
puts enc.inspect
# output: "\uFEFF\u0633\u0644\u0627\u0645"
# => nil