无法使用原始IO :: console

时间:2016-11-21 14:57:50

标签: ruby io console

我正在尝试在循环中使用IO::console::getch从控制台获取输入,但getch似乎没有捕获第一个换行符(我需要输入两次才能使循环中断)虽然getc确实如此,但与我想要做的其他事情无关。

如何捕获第一个CRLF,这样我就不需要输入两次?

相关代码:

require 'io/console'

buffer,str=IO::console(),""
loop do
    buffer.write "\r\033[32m"+str+"\033[0m"
    chr=buffer.getch

    break if chr=="\r"
    str+=chr
end
print "\n"+str

1 个答案:

答案 0 :(得分:1)

在查看Highline系统扩展模块的源代码后,我发现我可以在Windows上使用WinAPI._getch,在Unix上使用STDIN.getbyte来完成我想要的到(显然不完整的代码,因为我还没有检查SIGINT或类似的东西)。

require 'highline/system_extensions'
include HighLine::SystemExtensions

# assign getchar as a lambda based on OS
if (/mingw|win|emx/=~RUBY_PLATFORM)!=nil
    getchar=lambda{WinAPI._getch} # Windows
else
    getchar=lambda{STDIN.getbyte} # Unix
end

str="" # empty string to start
loop do
    # write the string to STDOUT in green as a test
    STDOUT.write "\r\033[32m"+str+"\033[0m"
    # call the lambda, convert to character
    chr=getchar[].chr

    return str if chr=="\r"
    str+=chr
end