I think it's a very small story, but I was at a loss for a long time because of unexpected information. I would like to participate in qiita little by little from such a place.
A program that displays what you get in Windows 10 + Ruby 2.7.0.
miss.rb
str = gets.chomp
puts str
That's all, but when I entered Japanese with puts, the characters were garbled. I usually use VS Code, and I thought it was compatible with the console and Ruby, but it didn't work at the command prompt. I messed with the encoding on the Ruby side, and while googled, I was confused by the old (obsolete) notation of ruby Ks, but in the end it was displayed safely when I did the following section.
correct.rb
STDIN.set_encoding "Windows-31J"
str = gets.chomp
puts str.encode("Windows-31J", invalid: :replace, replace: '')
After all,
--Windows console input / output encoding is Windows-31J ――So, first, adjust the character code of Ruby's standard input to match it (1st line) ――However, if you leave it as it is, characters that do not make sense will be attached at the beginning, so I will drop this in the description on the third line.
That (I think).
However, this is not perfect, and if gets contains double-byte characters, line breaks will not be recognized well and you will end up pressing the Enter key twice. I don't know this workaround for now. Well, it's not a behavior that I care about, so for now I'll try to survive with this.
Recommended Posts