2

I want to create a fake percent counter within terminal in Ruby somewhat like this:

percent = 0
(1..100).each{|x| sleep(0.05); print "#{percent+=1}%"}

How do I make it so that instead of printing percent over and over again it just increasing the value of percent by 1 but stays "in place".

Please note that this is for aesthetic purposes only.

Thanks

Lasonic
  • 841
  • 2
  • 9
  • 28

1 Answers1

4

You just need to add the carriage return character (e.g \r) to the end of the string, this has the effect of clearing the line before you write to it again.

percent = 0
(1..100).each{|x| sleep(0.05); print "#{percent+=1}%\r"}

What it actually does is a bit more complex and there's a good explanation here.

Community
  • 1
  • 1
Pete
  • 2,196
  • 1
  • 17
  • 25