Ruby 中文编码

Ruby 教程 · 2019-02-18 21:13:28

前面章节中我们已经学会了如何用 Ruby 输出 "Hello, World!",英文没有问题,但是如果你输出中文字符"你好,世界"就有可能会碰到中文编码问题。

Ruby 文件中如果未指定编码,在执行过程会出现报错:

#!/usr/bin/ruby -w

puts "你好,世界!";

以上程序执行输出结果为:

invalid multibyte char (US-ASCII) 

以上出错信息显示了 Ruby 使用用 ASCII 编码来读源码,中文会出现乱码,解决方法为只要在文件开头加入 # -*- coding: UTF-8 -*-(EMAC写法) 或者 #coding=utf-8 就行了。

实例

#!/usr/bin/ruby -w # -*- coding: UTF-8 -*- puts "你好,世界!";

输出结果为:

你好,世界!

所以如果大家再学习过程中,源代码文件中,若包含中文编码,则需要注意两点:

  • 1. 必须在首行添加 # -*- coding: UTF-8 -*-,告诉解释器使用utf-8来解析源码。
  • 2. 必须设置编辑器保存文件的编码为utf-8。

点击查看所有 Ruby 教程 文章: https://www.codercto.com/courses/l/16.html

查看所有标签

A Byte of Python

A Byte of Python

Swaroop C H / Lulu Marketplace / 2008-10-1 / USD 27.98

'A Byte of Python' is a book on programming using the Python language. It serves as a tutorial or guide to the Python language for a beginner audience. If all you know about computers is how to save t......一起来看看 《A Byte of Python》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

在线进制转换器
在线进制转换器

各进制数互转换器

URL 编码/解码
URL 编码/解码

URL 编码/解码