Console is a helper class for displaying super-ASCII strings on the console.

Console is necessary when you want to mix multi-column (e.g. Chinese, Japanese and Korean characters) and single-column (e.g. ASCII, Latin, Vietnamese) characters on screen in such a way that the display width matters. This is typically the case in curses programs with i18n support, but can be necessary in certain internationalized $stdout applications as well.

Note that display width is different from a) the number of bytes in the string, and b) the number of characters in the string. When you move beyond ASCII strings, these three metrics can all have distinct values for a given string.

The Console gem currently provides these methods:

  • Console.init_locale!: set the program's locale from the appropriate environment variables. (Ruby 1.8 programs must call this before calling any of the other methods. Ruby 1.9 programs can call it or skip it without effect.)

  • Console.display_width: calculates the display width of a string

  • Console.display_slice: returns a substring according to display offset and display width parameters.

If you require 'console', you will get just those methods.

If you require 'console/string', you will get String#display_width and String#display_slice methods directly on all strings.


## encoding: UTF-8 (this comment required for ruby 1.9)
require 'rubygems' # this line required for ruby 1.8
require 'console'
require 'console/string'


STRING = "我能吞下玻璃而不傷身體。Góa ē-tàng chia̍h po-lê, mā bē tio̍h-siong.私はガラスを食べられます。それは私を傷つけません。I can eat glass and it doesn't hurt me."
COLS = 30

rows = STRING.display_width / COLS
(0 .. rows).each { |i| puts STRING.display_slice(i * COLS, COLS) }

The result will be displayed in an even 30-column block on the console, even though some characters in the string require two columns to display and some characters require one column.


The console homepage is The console git repo is git://