Ruby Chinese Encoding
In the previous chapters we learned how to output "Hello, World!" with Ruby. English is fine, but if you output Chinese characters such as "Nihao, Shijie", you may run into Chinese encoding problems.
If no encoding is specified in a Ruby file, an error will occur during execution:
#!/usr/bin/ruby -w
puts "你好,世界!";
The 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 as garbled text. The solution is simply to add at the beginning of the file # -- coding: UTF-8 --(EMACS notation) or #coding=utf-8 and that's all.
Example
!/usr/bin/ruby -w
-- coding: UTF-8 --
puts
"
Hello, world!
"
;
Run Example »
The output is:
你好,世界!
So if, in the learning process, your source code files contain Chinese encoding, you need to pay attention to two points:
-
- You must add on the first line # -- coding: UTF-8 --, to tell the interpreter to use utf-8 to parse the source code.
-
- You must set your editor to save files with utf-8 encoding.