Clearing the Screen

Table of contents:

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.



Strings

Numbers

Date and Time

Arrays

Hashes

Files and Directories

Code Blocks and Iteration

Objects and Classes8

Modules and Namespaces

Reflection and Metaprogramming

XML and HTML

Graphics and Other File Formats

Databases and Persistence

Internet Services

Web Development Ruby on Rails

Web Services and Distributed Programming

Testing, Debugging, Optimizing, and Documenting

Packaging and Distributing Software

Automating Tasks with Rake

Multitasking and Multithreading

User Interface

Extending Ruby with Other Languages

System Administration



Ruby Cookbook
Ruby Cookbook (Cookbooks (OReilly))
ISBN: 0596523696
EAN: 2147483647
Year: N/A
Pages: 399

Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net