Clearing the Screen
Problem
You e writing a console application, and you want it to clear the screen.
Solution
Capture the output of the Unix clear command as a string and print it whenever you want to clear the screen:
#!/usr/bin/ruby -w # clear_console.rb clear_code = %x{clear} puts Press enter to clear the screen. $stdin.gets print clear_code puts "Its cleared!"
Discussion
The clear command prints an escape code sequence to standard output, which the Unix terminal interprets as a clear-screen command. The exact string depends on your terminal, but its probably an ANSI escape sequence, like this:
%x{clear} # => "e[He[2J"
Your Ruby script can print this escape code sequence to standard output, just as the clear command can, and clear the screen.
On Windows, the command is cls, and you can just print its standard output to clear the screen. Every time you want to clear the screen, you need to call out to cls with Kernel#system:
# clear_console_windows.rb puts Press enter to clear the screen. $stdin.gets system(cls) puts "Its cleared!"
If youve made your Windows terminal support ANSI (see Recipe 21.8), then you can print the same ANSI escape sequence used on Unix.
The Curses library makes this a lot more straightforward. A Curses application can clear any of its windows with Curses::Window#clear. Curses::clear will clear the main window:
#!/usr/bin/ruby -w # curses_clear.rb require curses Curses.init_ screen Curses.setpos(0,0) Curses::addstr("Type all you want. C clears the screen, Escape quits. ") begin c = nil begin c = Curses.getch end until c == ?C or c == ?e Curses.clear end until c == ?e
But, as always, Curses takes over your whole application, so you might want to just use the escape sequence trick.
Категории