Ruby compatibility error encoding

2019-06-13 14:15发布

I'm having a problem. Let's look:

C:\temp> ruby script.rb

script.rb                 => Powershell output

puts "ę"                  => ę #irb \xA9
puts "\xA9"               => ▯
puts "ę"=="\xA9"          => false
input = $stdin.gets.chomp => input=="ę"
puts "e#{input}e"         => eęe
puts "ę"==input           => false
puts "ę#{input}"          => Encoding::Compatibility Error Utf8 & CP852

irb                       => #command line in ruby
puts "ę"=="\xA9"          => true
input = $stdin.gets.chomp => input=="ę"
puts "ę"==input           => true  && "\xA9"==input => true
puts "ę#{input}"          => ęę

It looks like powershell's input uses other font for all special characters than ruby and notepad++(?). Can i change that so it will work when i type in prompt(when asked) and does not show an error?

Edit: Sorry for misdirection. I added invoke and specified that file has extension ".rb" not ".txt"
Edit2: Ok, I've researched some more information and I've been trying do some encoding(UTF8) to a variable. Somethin' strange occured.

puts "ę#{input.encoding}"         => ęCP852
puts "\xA9"                       => UTF-8

Encoding to CP852 has revealed that encoding pass on bytes. I learned that value of "ę"=20+99=119, "ą" = 20 + 85, 20 = C4

Ok. got it ".encoding" - shows what encoding i use. And that resolve this problem.

puts "ę#{input.encode "UTF-8"}"         => ęę

Thanks everyone for your input.

1条回答
混吃等死
2楼-- · 2019-06-13 14:44

If your input in prompt( either cmd or powershell) is causing problems due to incompatibility of using differents encodings just try to encode it via methods in script.encode "UTF-8" #in case of Ruby language If you dont know what methods do that just google your_language_name encoding

查看更多
登录 后发表回答