Ruby Output Unicode Character

旧巷老猫 提交于 2019-11-30 11:47:01

问题


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 mark as discussed in this blog.

The problem is if I do:

checkmark = "\u2713"
puts checkmark

It outputs "\u2713" 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?

EDIT


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


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


回答1:


In Ruby 1.9.x+

Use String#encode:

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

prints

In Ruby 1.8.7

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



回答2:


falsetru's answer is incorrect.

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.)

The correct answer is:

puts checkmark.force_encoding('utf-8')

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




回答3:


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

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

Just make sure you use double quotes!




回答4:


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

    <%= "\u00BD" %>

Much appreciation




回答5:


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

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


来源:https://stackoverflow.com/questions/18492664/ruby-output-unicode-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!