Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Output Unicode Character

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.

Unicode Check Mark U+2713

like image 558
Jeremy Harris Avatar asked Aug 28 '13 15:08

Jeremy Harris


People also ask

What does 𒈙 mean?

Symbol meaningCuneiform Sign Lugal Opposing Lugal.

How do I encode in Ruby?

Ruby defaults to UTF-8 as its encoding so if it is opening up files from the operating system and the default is different from UTF-8, it will transcode the input from that encoding to UTF-8. If this isn't desirable, you may change the default internal encoding in Ruby with Encoding.


2 Answers

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') } ✓ 
like image 79
falsetru Avatar answered Sep 29 '22 07:09

falsetru


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.

like image 30
zw963 Avatar answered Sep 29 '22 07:09

zw963