Latest web development tutorials

Ruby Chinese encoding

Ruby Chinese encoding

Previous chapters we have learned how to use Ruby output "Hello, World!", English no problem, but if you output Chinese characters "Hello, World" is likely to encounter Chinese coding problem.

Ruby files if the encoding is not specified in the implementation process will be given:

#!/usr/bin/ruby -w

puts "你好,世界!";

The above program execution output is:

invalid multibyte char (US-ASCII) 

The above error message shows the Ruby use with ASCII encoding to read the source, the Chinese will be garbled, the solution is just the beginning of the file on# - * - coding: UTF- 8 - * - (EMAC written) or # coding = utf-8on the line.

Examples

#! / Usr / bin / ruby ​​-w
# - * - Coding: UTF-8 - * -

puts "Hello, world!";

Running instance »

The output is:

你好,世界!

So if we re-learning process, the source code file, then with the Chinese encoding, you need to pay attention to two things:

  • 1. The first line must be added# - * - coding: UTF-8 - * -, tells the interpreter to use utf-8 to parse the source code.
  • 2. The editor must be set to save the file encoded as utf-8.