Recipe 21.3. Getting Input One Character at a TimeProblemYou're writing an interactive application or a terminal-based game. You want to read a SolutionMost Ruby installations on Unix come with the the Curses extension installed. If Curses has the features you want to write the rest of your program, the simplest solution is to use it. This simple Curses program echoes every key you type to the top-left corner of the screen. It stops when you hit the escape key (\e).[1]
If you don't want Curses to take over your program, you can use the HighLine library instead (available as the highline gem). It does its best to define a get_
Be careful; ask echoes a newline after every character it receives.[2] That's why I use a print statement in that example instead of puts.
Of course, you can avoid this annoyance by hacking the HighLine class to make get_character public:
DiscussionThis is a huge and complicated problem that (fortunately) is completely hidden by Curses and HighLine. Here's the problem: Unix systems know how to talk to a lot of historic and modern terminals. Each one has a different feature set and a different command language. HighLine (through the Termios library it uses on Unix) and Curses hide this complexity. Windows doesn't have to deal with a lot of terminal types, but Windows programs don't usually read from standard input either (much less one character at a time). To do single-
HighLine also has two definitions f get_character for Unix; you can copy one of these if you don't want to require HighLine. The most reliable implementation is fairly complicated, and requires the termios gem. But if you need to require the termios gem, you might as well require the highline gem as well, and use HighLine's implementation as is. So if you want to do single-character input on Unix without requiring any gems, you'll need to rely on the Unix command stty:
All of the HighLine code is in the main highline.rb file; search for "get_character". See Also
|
Thursday, October 29, 2009
Recipe 21.3. Getting Input One Character at a Time
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment