Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print unicode charaters in Command Prompt with Ruby

I was wondering how to print unicode characters, such as Japanese or fun characters like šŸ“¦.

I can print hearts with:

hearts = "\u2665"
puts hearts.encode('utf-8')

How can I print more unicode charaters with Ruby in Command Prompt?
My method works with some characters but not all.

Code examples would be greatly appreciated.

like image 385
Adjam Avatar asked Sep 10 '25 21:09

Adjam


1 Answers

You need to enclose the unicode character in { and } if the number of hex digits isn't 4 (credit : /u/Stefan) e.g.:

heart = "\u2665"
package = "\u{1F4E6}"
fire_and_one_hundred = "\u{1F525 1F4AF}"
puts heart
puts package
puts fire_and_one_hundred

Alternatively you could also just put the unicode character directly in your source, which is quite easy at least on macOS with the Emoji & Symbols menu accessed by Ctrl + Command + Space by default (a similar menu can be accessed on Windows 10 by Win + ; ) in most applications including your text editor/Ruby IDE most likely:

macOS Emoji Menu

heart = "♄"
package = "šŸ“¦"
fire_and_one_hundred = "šŸ”„šŸ’Æ"
puts heart
puts package
puts fire_and_one_hundred

Output:

♄
šŸ“¦
šŸ”„šŸ’Æ

How it looks in the macOS terminal:

How it looks in the macOS terminal

like image 179
Sash Sinha Avatar answered Sep 13 '25 12:09

Sash Sinha