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

查看所有标签

The Tangled Web

The Tangled Web

Michal Zalewski / No Starch Press / 2011-11-26 / USD 49.95

"Thorough and comprehensive coverage from one of the foremost experts in browser security." -Tavis Ormandy, Google Inc. Modern web applications are built on a tangle of technologies that have been de......一起来看看 《The Tangled Web》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具