Ruby Chinese encoding

Ruby Chinese encoding

Previous chapters we have learned how to output "Hello, World!" With Ruby, English is no problem, but if you output Chinese characters "Hello, world" is likely to encounter Chinese coding problem.
Ruby file if the encoding is not specified, an error occurs during the execution:

#!/usr/bin/ruby -w

puts "你好,世界!";

More execution output is:

invalid multibyte char (US-ASCII)

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

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

puts "你好,世界!";

The output is:

你好,世界!

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

  1. # Must be added in the first line - - Coding: UTF-8 - -, told the interpreter uses utf-8 to parse the source code.
  2. You must set the editor to save the file encoded as utf-8.
    This switched; http://codingdict.com/article/6829

Guess you like

Origin www.cnblogs.com/bczd/p/11980953.html