3

绝对必须有更好的方法来做到这一点。

temp_file ||= Tempfile.new()
system("stty -echo; tput u7; read -d R x; stty echo; echo ${x#??} > #{temp_file.path}")
temp_file.gets.chomp.split(';').map(&:to_i)

基本上,我在子进程中运行这个问题的 bash 脚本,然后从重定向文件中读取输出。

不使用 C 或任何 gem(stdlib 可以)有什么更好的方法来做到这一点?交叉兼容性不是很重要。

4

3 回答 3

2

curses在标准库中,但它是一团糟。

于 2011-04-27T20:30:35.240 回答
2

这是获取光标位置的纯 ruby​​ 实现:

require 'io/console'

class Cursor
  class << self
    def pos
      res = ''
      $stdin.raw do |stdin|
        $stdout << "\e[6n"
        $stdout.flush
        while (c = stdin.getc) != 'R'
          res << c if c
        end
      end
      m = res.match /(?<row>\d+);(?<column>\d+)/
      { row: Integer(m[:row]), column: Integer(m[:column]) }
    end
  end
end

puts Cursor.pos  #=> {:row=>25, :column=>1}

tput u7被替换为回显\e[6n$stdout。它可能不太便携,但可以帮助我们仅使用 ruby​​ 代码。

于 2015-05-01T17:24:11.947 回答
0

https://github.com/eclubb/ncurses-ruby

你可以在 Ruby 中试试这个。它似乎有你需要的 curX 和 curY 东西。

于 2011-04-27T20:32:07.507 回答