I would like to be able to output two lines to the terminal and then delete both of them. I know you can do one by doing something like
print "\b"*whatever
but I would like to do something more like this:
[1, 2, 3, 4, 5].each do |item|
# code to delete the previous two lines
print item.to_s + "\nHello!"
end
The output would quickly go through all of the following
1
Hello!
2
Hello!
3
Hello!
4
Hello!
5
Hello!
but by the end, the final iteration would be all you see.
Well, for simple things, if you can assume an ANSI-compatible terminal (usually a good bet), you can just directly output ANSI codes. For instance,
5.times do |item|
print "\r" + ("\e[A\e[K"*3) if item > 0
puts "#{item+1}\nHello!"
end
Where \r
moves the cursor to the start of the line, \e[A
moves the cursor up one line, and \e[K
clears from the cursor position to the end of the line. If you don't need anything further down the screen, you can also just send \e[J
once you have the cursor where you want; that clears all the way to the end of the screen.
For more sophisticated stuff, you could start by taking a look at the Highline gem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With