Saturday, May 28, 2022

[SOLVED] How to overwrite a printed line in the shell with Ruby?

Issue

How would I overwrite the previously printed line in a Unix shell with Ruby?

Say I'd like to output the current time on a shell every second, but instead of stacking down each time string, I'd like to overwrite the previously displayed time.


Solution

You can use the \r escape sequence at the end of the line (the next line will overwrite this line). Following your example:

require 'time'

loop do
  time = Time.now.to_s + "\r"
  print time
  $stdout.flush
  sleep 1
end


Answered By - cam
Answer Checked By - Mildred Charles (WPSolving Admin)