Ruby Output Unicode Character Ruby Output Unicode Character ruby ruby

Ruby Output Unicode Character


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


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.


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!