绝对有更好的方法来做到这一点。
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)
基本上,我从 this question 运行 bash 脚本在子进程中,然后从重定向文件中读取输出。
在不使用 C 或任何 gems(stdlib okay)的情况下,有什么更好的方法来做到这一点?交叉兼容性不是很重要。
最佳答案
这是获取光标位置的纯 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 代码。
关于ruby - 从 Ruby 获取终端位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5810131/