brian yahn wrote:
> Eric Hodel wrote:
>> On Mar 26, 2006, at 6:52 PM, yahn wrote:
>>
>>> How do you do something like gets but without blocking?  All I want to
>>> do is try to see if anything was input and if it wasn't then just  
>>> go on
>>> running the rest of my code.
>> Use threads.
>>
>> In one thread perform your IO.  In your other thread do whatever it
>> is you'd like to do while waiting for IO.
>>
>> --
>> Eric Hodel - drbrain / segment7.net - http://blog.segment7.net
>> This implementation is HODEL-HASH-9600 compliant
>>
>> http://trackmap.robotcoop.com
> 
> Ok thats one way to do it, but doesn't ruby have an actual way of just 
> seeing if any input has been performed?  Unnecessary threads will just 
> slow down the program.
> 

A thread won't cost much if it is just waiting for input.

If the other tasks that are being handled by your program are driven by
IO, then you could use select from a single one thread. (That's more or
less what is going on when you have multiple ruby threads each handling
their own IO.)

Or you could use select with a timeout of 0 to check if input is
available on $stdin.

print "type something> "; $stdout.flush
loop do
  sleep 0.1; print "."; $stdout.flush
  if IO.select([$stdin], [], [], 0)
    str = $stdin.gets
    break unless str
    puts "You typed #{str.inspect}"
    print "type something> "; $stdout.flush
  end
end

The #sleep call and the print "." is just to emulate the effect of the
program running while the user is typing.

However, I expect that it will be easier to make the program feel
responsive if you use threads, and let ruby's thread scheduler handle
the timing.

-- 
      vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407