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

Solution 1:

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

Solution 2:

Use the escape sequence \r at the end of the line - it is a carriage return without a line feed.

On most unix terminals this will do what you want: the next line will overwrite the previous line.

You may want to pad the end of your lines with spaces if they are shorter than the previous lines.

Note that this is not Ruby-specific. This trick works in any language!

Solution 3:

Here is an example I just wrote up that takes an Array and outputs whitespace if needed. You can uncomment the speed variable to control the speed at runtime. Also remove the other sleep 0.2 The last part in the array must be blank to output the entire array, still working on fixing it.

#@speed = ARGV[0]

strArray = [ "First String there are also things here to backspace", "Second Stringhereare other things too ahdafadsf", "Third String", "Forth String", "Fifth String", "Sixth String", " " ]


#array = [ "/", "-", "|", "|", "-", "\\", " "]

def makeNewLine(array)
    diff = nil
    print array[0], "\r"
    for i in (1..array.count - 1)
        #sleep @speed.to_f
        sleep 0.2
        if array[i].length < array[i - 1].length
             diff = array[i - 1].length - array[i].length
        end
        print array[i]
        diff.times { print " " } if !diff.nil?
        print "\r"
        $stdout.flush

    end
end

20.times { makeNewLine(strArray) }

#20.times { makeNewLine(array)}