How to get the width of terminal window in Ruby

前端 未结 9 1483
你的背包
你的背包 2021-01-30 16:30

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 Rub

相关标签:
9条回答
  • 2021-01-30 17:15

    Ruby actually comes with a built-in class called "Curses", which lets you do all kinds of things with the terminal window.

    For example, you can do this:

    require 'curses'
    
    Curses.init_screen()
    
    puts Curses.lines # Gives you the height of terminal window
    puts Curses.cols # Gives you the width of terminal window
    

    For more info: http://ruby-doc.org/stdlib-1.9.3/libdoc/curses/rdoc/Curses/Window.html

    0 讨论(0)
  • 2021-01-30 17:17

    If you want your code to work across platforms, here's what I use: http://github.com/cldwalker/hirb/blob/master/lib/hirb/util.rb#L61-71

    Also check out the system_extensions file in highline

    0 讨论(0)
  • 2021-01-30 17:18

    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

    0 讨论(0)
提交回复
热议问题