开发者

How does one determine console character width from ruby program?

开发者 https://www.devze.com 2022-12-21 07:07 出处:网络
I wa开发者_运维知识库nt to print columnar output from a ruby program, but in order to take full advantage of the available screen space, I need to determine the character width of the terminal the pro

I wa开发者_运维知识库nt to print columnar output from a ruby program, but in order to take full advantage of the available screen space, I need to determine the character width of the terminal the program is running in. How does one do this?


The HighLine gem uses this function to find the dimensions of a terminal:

  # A Windows savvy method to fetch the console columns, and rows.
  def terminal_size
    stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE)

    bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy =
    GetConsoleScreenBufferInfo(stdout_handle)
    return right - left + 1, bottom - top + 1
  end

This method should work also on Windows, if you use Linux (or something similar) only then you can use stty size to find the dimensions more easily using something like:

def terminal_size
  `stty size`.split.map { |x| x.to_i }.reverse
end
0

精彩评论

暂无评论...
验证码 换一张
取 消