Ruby Chinese coding
In the previous chapter, we have learned how to use Ruby to output "Hello, World!". There is no problem in English, but if you output the Chinese characters "Hello, World", you may encounter Chinese encoding problems.
If the encoding is not specified in the Ruby file, an error will appear during the execution process:
#!/usr/bin/ruby -w puts "你好,世界!";
The output result of the above program execution is:
invalid multibyte char (US-ASCII)
The above error message shows the Ruby usage When reading the source code using ASCII encoding, Chinese characters will appear garbled. The solution is to add # -*- coding: UTF-8 -*- (EMAC writing method) at the beginning of the file or #coding=utf- 8 will do.
Instance
#!/usr/bin/ruby -w # -*- coding: UTF-8 -*- puts "你好,世界!";
Run Instance»
Click the "Run Instance" button to view the online instance
The output result is:
你好,世界!
So if you are still learning, if the source code file contains Chinese encoding, you need to pay attention to two points:
1. You must add # -*- coding: UTF-8 -*- in the first line to tell the interpreter to use utf-8 to parse the source code.
2. The encoding of the file saved by the editor must be set to utf-8.