提问人:Sercan Tırnavalı 提问时间:6/24/2021 更新时间:6/25/2021 访问量:426
Windows 10 终端输入上的 Ruby irb utf-8 编码问题
Ruby irb utf-8 encoding problem on windows 10 terminal input
问:
我想在我的窗口中使用带有终端输入的 ruby。为什么 ruby 社区不能在 Windows 上解决这个 UTF-8 问题?难吗?我想知道 python、java 或其他语言是如何做到这一点的?我可以毫不费力地在 Windows utf-8 上使用 python。
使用 ruby 3.0.1
x = gets.chomp
çağrı
=> "\x87a\xA7r\x8D"
puts x
�a�r�
=> nil
x.valid_encoding?
=> false
我查了一下这个 https://bugs.ruby-lang.org/issues/16604 它没有用。
答:
2赞
Holger Just
6/24/2021
#1
在 Ruby 3.0 中,默认的外部编码(即从 ruby 进程外部读取的任何数据的假定编码,例如在 Windows 上使用 shell 时从 shell 读取的编码)更改为 UTF-8。这是对 Windows 上编码时出现的各种问题的回应。gets)
但是,您从 shell 中读取的数据不是 UTF-8 编码的。相反,您的 shell 似乎使用了一些不同的编码,例如 .cp850
一种可能的解决方法是指示 Ruby 采用环境的语言环境编码,您可以使用命令调用中的开关进行设置,例如:-E
irb -E locale
或者通过在脚本中手动设置为环境的正确编码。Encoding.default_external
0赞
Sercan Tırnavalı
6/25/2021
#2
在土耳其语 Windows PC 的 cmd shell 使用 CP857 编码
您可以在 cmd >首选项部分看到它
这是Holger贡献的实践解决方案。
irb(main):005:0> x = gets.chomp
Here is the Turkish chars ğĞüÜşŞiİıIöÖçÇ
=> "Here is the Turkish chars \xA7\xA6\x81\x9A\x9F\x9Ei\x98\x8DI\x94\x99\x87\x80"
irb(main):006:0> x.force_encoding "CP857"
=> "Here is the Turkish chars \xA7\xA6\x81\x9A\x9F\x9Ei\x98\x8DI\x94\x99\x87\x80"
irb(main):007:0> x.valid_encoding?
=> true
irb(main):008:0> x.encode("UTF-8", undef: :replace)
=> "Here is the Turkish chars ğĞüÜşŞiİıIöÖçÇ"
评论