Ruby Chinese code

In the previous sections we learned how to output "Hello, World!" with Ruby, no problem in English, but if you output the Chinese character "Hello, world" you may run into Chinese coding problems.

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

#!/usr/bin/ruby -w

puts "你好,世界!";

The output of the above program execution is:

invalid multibyte char (US-ASCII) 

The error information above shows that Ruby uses ASCII encoding to read the source code, and the Chinese will be garbled, as long as you add the word "-coding: UTF-8- - (EMAC writing) or #coding-utf-8 at the beginning of the file."

#!/usr/bin/ruby -w
# -*- coding: UTF-8 -*-

Puts "Hello, world!"

Run an instance . . .

The output is:

你好,世界!

So if you re-learn the process, the source code file, if Chinese code, you need to pay attention to two points:

  • 1. You must add the first line of the .
  • 2. The editor must be set to encode the saved file as utf-8.