Ruby Chinese encoding

In the previous chapters we have learned how to output "Hello, World!" in Ruby. There is no problem in English, but if you output the Chinese character "Hello, the world" is possible Will encounter Chinese coding problems.

If no encoding is specified in the Ruby file, an error will occur during execution:

#!/usr/bin/ruby -w

Puts "Hello, the world!";

The above program execution output is:

invalid multibyte char (US-ASCII ) 

The above error message shows that Ruby uses ASCII encoding to read the source code. Chinese will be garbled. The solution is to add # -*- coding: UTF-8 -*- at the beginning of the file. EMAC) or #coding=utf-8 will do.


#!/usr/bin/ruby -w # -*- coding: UTF-8 -*- puts "Hello, the world!";

The output is:

Hello, the world! 

So if you are learning again, if you include Chinese code in the source code file, you need to pay attention to two points:

  • 1. You must add # -*- coding: UTF-8 -*- to the first line to tell the interpreter to use utf-8 to parse the source code.
  • 2. The code of the editor save file must be set to utf-8.

welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.