Adjam
Adjam

Reputation: 640

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.

Upvotes: 4

Views: 1428

Answers (1)

Sash Sinha
Sash Sinha

Reputation: 22350

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

Upvotes: 6

Related Questions