How to blink a text with Ruby
Was building a Ruby game recently and wanted to add a small animation on the console. Then i thought of blinking.
The process of blinking is as follows ;
- print a text on screen;
- delete that text after some seconds;
- Repeat the above two processes in a loop, and the effect is blink. (see code bellow):
msg = 'game over!!!' #<---message to be printed5.times do #<----- loops 5 times
print "\r#{msg}"
sleep 0.5 #<----message stays for 0.5 seconds
print "\r #{' ' * msg.size}\r" #<-----wiping screen
sleep 0.5
end
puts msg #<------optional
You can save this code in a file blink.rb
and run the file in your terminal to see results with commands ruby blink.rb
(Ruby must be installed)
N.B
“\r” option is very important, it makes the text to always be printed in the start of the console (demonstration below):
1- print "first"; print "second" <-- shows "firstsecond" on console
2- print "\rfirst"; print "\rsecond" <-- shows "second" on console
First line prints “first”, then “second” just immediately
Second line prints “first”, returns cursor to start of line (wiping effect), then prints “second”.