How to get the width of terminal window in Ruby

Viewed 13847

Have you ever noticed that if you run rake -T in rails the list of rake descriptions are truncated by the width of the terminal window. So there should be a way to get it in Ruby and Use it.

I'm printing some Ascii-art on the screen and I don't want it to be broken. therefore I need to find out the width of terminal at run time some how.

Any Idea how to do that?

9 Answers

There is a common unix command:

tput cols

This returns the width of the terminal.

    require 'io/console'
    puts "Rows by columns: #{IO.console.winsize}"
    puts "Ruby 2.6.4"

ENV['COLUMNS'] will give you the number of columns in the terminal.

I wrote the tty-screen gem to detect terminal size across different OS systems and Ruby interpreters. It covers many ways of checking the size including Win API on Windows, Java libs on JRuby and Unix utilities.

This is a module which you can include in your class or call directly:

require 'tty-screen'

TTY::Screen.size     # => [51, 280]
TTY::Screen.width    # => 280
TTY::Screen.height   # => 51

For more info see: https://github.com/piotrmurach/tty-screen

Related