Easy Tutorial
❮ Ruby Dir Methods Ruby Dbi Read ❯

Ruby Chinese Encoding

In previous chapters, we have learned how to output "Hello, World!" in Ruby, which works fine in English. However, if you try to output Chinese characters like "你好,世界", you may encounter Chinese encoding issues.

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

#!/usr/bin/ruby -w

puts "你好,世界!";

The above program execution output is:

invalid multibyte char (US-ASCII)

The error message indicates that Ruby uses ASCII encoding to read the source code, which causes Chinese characters to appear as乱码. The solution is to add # -- coding: UTF-8 -- (EMACS style) or #coding=utf-8 at the beginning of the file.

Example

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

puts "你好,世界!";

The output result is:

你好,世界!

So, if you are learning Ruby and your source code file contains Chinese characters, you need to pay attention to two points:

❮ Ruby Dir Methods Ruby Dbi Read ❯