How do you clear the IRB console screen?
21 Answers
Just discovered this today: in Pry (an IRB alternative), a line of input that begins with a . will be forwarded to the command shell. Which means on Mac & Linux, we can use:
. clear
And, on Windows (Command Prompt and Windows Terminal), we can use:
. cls
Source: pry.github.io
Windows users simply try,
system 'cls'
OR
system('cls')
Looks like this in the IRB window,
irb(main):333:0> system 'cls'
irb(main):007:0> system('cls')
Did the trick for me in ruby 1.9.3. However the following commands did not work and returned => nil,
system('clear')
system 'clear'
system `cls` #using the backquotes below ESC Key in windows
Tons of good answers here, but I often remote into a linux box with Mintty from windows. Kudos to the above about using .irbrc, but came up with this:
def cls
puts "\ec\e[3J"
end
def clear
puts "\e[H\e[2Js"
end
This gives you the options for both the *nix 'clear' behavior and the Windows 'cls' behavior, which I often find more useful if I really want to nuke the buffer rather than just scrolling it out of view.
P.S. a similar variant also works in .bashrc:
alias cls='echo -e "\ec\e[3J"'
If anyone could find a way to actually map that to a keystroke, I'd love to hear it. I would really like to have something akin to cmd-k on osx that would work in Mintty.
->(a,b,c){x=a.method(b);a.send(c,b){send c,b,&x;false};print"\e[2J\e[H \e[D"}[irb_context,:echo?,:define_singleton_method]
This will fully clear your IRB screen, with no extra empty lines and “=> nil” stuff. Tested on Linux/Windows.
This one-liner could be expanded as:
lambda {
original_echo = irb_context.method(:echo?)
irb_context.send(:define_singleton_method, :echo?) {
send :define_singleton_method, :echo?, &original_echo
false
}
print "\e[2J\e[H \e[D"
}.call
This uses lots of tricks.
Firstly, irb will call echo? to check if the result should be printed. I saved the method, then redefined with a method which restores the defination but returns false so irb will not echo the result.
Secondly, I printed some ANSI control chars. \e[2J will clean the screen and \e[H will move the cursor to the upper left position of the screen. \e[D will print a space and then move back the cursor while this is a workaround for something strange on Windows.
Finally this is kind of not practical at all. Just smile ;)