简体   繁体   English

Ruby 输出 Unicode 字符

[英]Ruby Output Unicode Character

I'm not a Ruby dev by trade, but am using Capistrano for PHP deployments.我不是 Ruby 开发人员,而是使用 Capistrano 进行 PHP 部署。 I'm trying to cleanup the output of my script and am trying to add a unicode check mark as discussed in this blog .我正在尝试清理脚本的输出,并尝试添加本博客中讨论的unicode 复选标记

The problem is if I do:问题是如果我这样做:

checkmark = "\u2713"
puts checkmark

It outputs "\✓" instead of ✓它输出“\✓”而不是✓

I've googled around and I just can't find anywhere that discusses this.我已经用谷歌搜索了,我找不到任何讨论这个的地方。

TLDR: How do I puts or print the unicode checkmark U-2713? TLDR:如何putsprint unicode 复选标记 U-2713?

EDIT编辑


I am running Ruby 1.8.7 on my Mac (OSX Lion) so cannot use the encode method.我在 Mac (OSX Lion) 上运行 Ruby 1.8.7,因此无法使用encode方法。 My shell is Bash in iTerm2.我的 shell 是 iTerm2 中的 Bash。


UPDATE [4/8/2019] Added reference image in case site ever goes down.更新[4/8/2019] 添加了参考图片,以防网站宕机。

Unicode 复选标记 U+2713

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') }
✓

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. 这会将当前系统编码的复选标记转码为UTF-8编码。 (That works only on a system whose default is already 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. 这会修改字符串的编码,而不会修改任何字符序列。

In newer versions of Ruby, you don't need to enforce encoding. 在较新版本的Ruby中,您不需要强制执行编码。 Here is an example with 2.1.2 : 这是2.1.2一个例子:

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

Just make sure you use double quotes! 只要确保你使用双引号!

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 非常欣赏

As an additional note, if you want to print an emoji, you have to surround it with braces. 另外请注意,如果要打印表情符号,则必须用大括号括起来。

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

How we can print as is in newer version of ruby我们如何在较新版本的 ruby​​ 中按原样打印

checkmark = "\✓" puts checkmark checkmark = "\✓" 放置复选标记

This should print AS IS \✓这应该按原样打印 \✓

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM