Ruby Chinese coding


Release date:2023-10-25 Update date:2023-10-25 Editor:admin View counts:218

Label:

Ruby Chinese coding

In the previous section, we have learned how to use Ruby to output “Hello, World!”. There is no problem with English, but if you output the Chinese character “Hello, World”, you may encounter Chinese coding problems.

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

#!/usr/bin/ruby -w

puts "Hello World!";

The output of the above program execution is as follows:

invalid multibyte char (US-ASCII)

The above error message shows that Ruby uses ASCII coding to read the sourcecode, and there will be garbled code in Chinese. The solution is as long asyou add # -*- coding: UTF-8 -*- (written in EMAC) or #coding=utf-8 just do it.

Example

#!/usr/bin/ruby -w#-*- coding: UTF-8 -*-puts"Hello World!";

The output is as follows:

Hello World!

Therefore, if you include a Chinese code in the source code file during the learning process, you need to pay attention to two points:

  • 1.Must be added on the first line # -*- coding: UTF-8 -*- tell the interpreter to use utf-8 to parse the source code

    1. You must set the editor to save the file’s encoding to utf-8.

Powered by TorCMS (https://github.com/bukun/TorCMS).