How can I clear the terminal in Ruby?

Solution 1:

If you want something that is vaguely portable you can try:

system "clear" || system "cls"

which will try both clear and cls

Solution 2:

Try any of these two in your ruby file:

puts `clear`

or

puts "\e[H\e[2J"

Solution 3:

Here is a multiplatform way to do it:

Gem.win_platform? ? (system "cls") : (system "clear")

Solution 4:

Edit: (rereading your question I realize this is not what you are after. I thought you were referring to the IRB. I will leave this here and not delete it as I feel it is can be very useful information)


Ultimately it depends what system you are on.

ctrl+l (<- that is a lower case L) will clear the terminal ( cmd+K on a mac I believe)

this also works in the regular terminal, or the python interprator, or mysql, etc

there are a fair amount of other shortcuts you may like to familiarize yourself with. i found this after a quick google search:

CTRL-l - Clears the screen and places the command prompt at the top of the page.
CTRL-r - Starts a search against the command history. Start by typing in what you want to search by then press CTRL-r to see the matches.
CTRL-c - Kills the current running foreground program.
CTRL-z - Stop/sleep the current running foreground program.
CTRL-s - Stops the output to the screen.
CTRL-q - Allows output to the screen.
CTRL-a - Moves the cursor the start of the line
CTRL-e - Moves the cursor to the end of the line
CTRL-f - Moves the cursor 1 character forward
CTRL-b - Moves the cursor 1 character backward

not mentioned on that list is that

Alt-F moves the curosor one word forward
Alt- B moves the cursor one word back