Ruby 输出 Unicode 字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18492664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:09:20  来源:igfitidea点击:

Ruby Output Unicode Character

rubystringunicodeutf-8ruby-1.8.7

提问by Jeremy Harris

I'm not a Ruby dev by trade, but am using Capistrano for PHP deployments. I'm trying to cleanup the output of my script and am trying to add a unicode check markas discussed in this blog.

我不是 Ruby 开发人员,而是使用 Capistrano 进行 PHP 部署。我正在尝试清理脚本的输出,并尝试添加本博客中讨论的unicode 复选标记

The problem is if I do:

问题是如果我这样做:

checkmark = "\u2713"
puts checkmark

It outputs "\u2713" instead of ?

它输出 "\u2713" 而不是 ?

I've googled around and I just can't find anywhere that discusses this.

我已经用谷歌搜索了,我找不到任何讨论这个的地方。

TLDR: How do I putsor printthe unicode checkmark U-2713?

TLDR:我如何putsprintunicode 复选标记 U-2713?

EDIT

编辑



I am running Ruby 1.8.7 on my Mac (OSX Lion) so cannot use the encodemethod. My shell is Bash in iTerm2.

我在 Mac (OSX Lion) 上运行 Ruby 1.8.7,因此无法使用该encode方法。我的 shell 是 iTerm2 中的 Bash。



UPDATE[4/8/2019] Added reference image in case site ever goes down.

更新[4/8/2019] 添加了参考图片,以防网站宕机。

Unicode Check Mark U+2713

Unicode 复选标记 U+2713

回答by falsetru

In Ruby 1.9.x+

在 Ruby 1.9.x+ 中

Use String#encode:

使用String#encode

checkmark = "\u2713"
puts checkmark.encode('utf-8')

prints

印刷

?

In Ruby 1.8.7

在 Ruby 1.8.7 中

puts '\u2713'.gsub(/\u[\da-f]{4}/i) { |m| [m[-4..-1].to_i(16)].pack('U') }
?

回答by zw963

falsetru's answer is incorrect.

falsetru 的答案是不正确的。

checkmark = "\u2713"
puts checkmark.encode('utf-8')

This transcodes the checkmark from the current system encoding to UTF-8 encoding. (That works only on a system whose default is already UTF-8.)

这会将选中标记从当前系统编码转码为 UTF-8 编码。(这仅适用于默认值已经是 UTF-8 的系统。)

The correct answer is:

正确答案是:

puts checkmark.force_encoding('utf-8')

This modifies the string's encoding, without modifying any character sequence.

这会修改字符串的编码,而不修改任何字符序列。

回答by sixty4bit

In newer versions of Ruby, you don't need to enforce encoding. Here is an example with 2.1.2:

在较新版本的 Ruby 中,您不需要强制编码。这是一个示例2.1.2

2.1.2 :002 > "\u00BD"
 => "?"

Just make sure you use double quotes!

只要确保你使用双引号!

回答by Blubber

As an additional note, if you want to print an emoji, you have to surround it with braces.

另外要注意的是,如果你想打印一个表情符号,你必须用大括号把它包围起来。

irb(main):001:0> "\u{1F600}"
=> ""

回答by killscreen

Same goes as above in ERB, no forced encoding required, works perfectly, tested at Ruby 2.3.0

与上面的 ERB 相同,不需要强制编码,完美运行,在 Ruby 2.3.0 上测试

    <%= "\u00BD" %>

Much appreciation

非常欣赏