---- Original message from Bill Kelly on 8/9/2005 10:25 AM:
From: "Bill Atkins" <batkins57@gmail.com>
How can I determine if there's input waiting on STDIN before
calling gets?
I use:
if WINDOWS_VERSION
require 'dl'
$win32_console_kbhit = Win32API.new("msvcrt", "_kbhit", , 'I')
def console_input_ready?
$win32_console_kbhit.call != 0
end
else
def console_input_ready?
select([$stdin], nil, nil, 0) != nil
end
end
Note that if you do a gets() when console_input_ready?
is true, you'll still block until the user hits <enter>.
BTW, I was using:
WINDOWS_VERSION = (RUBY_PLATFORM =~ /win32/) != nil
You can also define '_getch' to allow you to get the character right away and not have to wait for the user to press the <enter> key.
require 'Win32API'
$win32_console_kbhit = Win32API.new("msvcrt", "_kbhit", , 'I')
$win32_console_cputs = Win32API.new("msvcrt", "_cputs", ['P'], 'I')
$win32_console_getch = Win32API.new("msvcrt", "_getch", , 'I')
def console_input_ready?
$win32_console_kbhit.call != 0
end
def console_input
$win32_console_getch.call
end
def console_output( str )
$win32_console_cputs.call( str )
end
while true
if console_input_ready? then
ch = console_input
print "ch: <#{ch.chr}>\n"
break
else
console_output( "." )
sleep 0.5
end
end