Ruby Chinese Encoding
In the previous chapters, we have already learned how to output "Hello, World!" with Ruby. There is no problem with English, but if you output the Chinese characters "hello,world", you may encounter Chinese encoding problems.
If the encoding is not specified in a Ruby file, an error will occur during execution:
#!/usr/bin/ruby -w puts "你好,世界!";
The execution output of the above program is:
invalid multibyte char (US-ASCII)
The above error message shows that Ruby uses ASCII encoding to read the source code, and Chinese characters will appear garbled. The solution is to add the following at the beginning of the file:# -*- coding: UTF-8 -*-(Emacs style) or#coding=utf-8is enough.
Example
#!/usr/bin/ruby -w
# -*- coding: UTF-8 -*-
puts "Hello, World!";
Run example »
The output is:
Hello, world!
Therefore, if your source code file contains Chinese encoding during the learning process, you need to note two points:
- 1. You must add at the first line:# -*- coding: UTF-8 -*-, which tells the interpreter to use utf-8 to parse the source code.
- 2. You must set the editor to save the file with encoding utf-8. Other Extensions