36

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

43

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') }
  • I should have mentioned I have Ruby 1.8.7 and apparently the encode method isn't available until 1.9. How was it done prior to 1.9? – Jeremy Harris Aug 28 '13 at 15:55
  • 1
    @cillosis, I added Ruby 1.8.7 compatible version. You should use '\u2713' or "\\u2713", because "\u2713" == "u2713" in ruby 1.8. – falsetru Aug 28 '13 at 16:03
  • 1
    Bam! I first tried your solution and it wasn't working. Then went to single quotes and it worked! Thanks :) – Jeremy Harris Aug 28 '13 at 16:07
  • I was able to simply do something like checkmark = "\u2713".encode('utf-8'); puts checkmark and so the encoding was saved to the variable. This works for me in Ruby 2.2.2. – HarlemSquirrel Jan 29 '16 at 19:06
  • @sixty4bit, If you want to notify OP, mention OP or comment on the question. Otherwise, OP will not be notified. – falsetru Nov 7 '16 at 1:29
16

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.

13

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!

0

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

    <%= "\u00BD" %>

Much appreciation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.