Encoding when getting in Windows + Ruby

This is the first post

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.

What I was worried about

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.

solution

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

Encoding when getting in Windows + Ruby
Change java encoding in windows
Be careful when omitting return in Ruby
Do not return when memoizing in Ruby
Class in Ruby
Heavy in Ruby! ??
About eval in Ruby
Getting Started with Ruby
Output triangle in Ruby
Correspondence when Ruby version does not switch in rbenv
Ruby on Rails Tutorial Troublesome notes when running on Windows
Variable type in ruby
Fast popcount in Ruby
Difficulties in building a Ruby on Rails environment (Windows 10) (SQLite3)
Resolve CreateProcess error = 206 when running Java in a Windows environment
Notes on character encoding when migrating from windows to Mac
ABC177 --solving E in Ruby
Validate JWT token in Ruby
Implemented XPath 1.0 parser in Ruby
Read design patterns in Ruby
Write class inheritance in Ruby
Update Ruby in Unicorn environment
Integer unified into Integer in Ruby 2.4
[Ruby] Exception handling in functions
Use ruby variables in javascript.
Multiplication in a Ruby array
About regular expressions in Ruby
Ruby Learning # 10 Getting User Input
Birthday attack calculation in Ruby
Judgment of fractions in Ruby
Find Roman numerals in Ruby
Try using gRPC in Ruby
Ruby ① Build a Windows environment
Getting Started with Ruby Modules
[Ruby] Find numbers in arrays
NCk mod p in Ruby
Chinese Remainder Theorem in Ruby
A memorial service for the library used when competing in Ruby
Breakpoint doesn't work when running Rails Minitest in Ruby Test Explorer