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

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 1:[1]

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 2:[2]

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)}

Solution 3:[3]

You can use

  1. Ruby module curses, which was part of the Ruby standard library

  2. Cursor Movement

puts "Old line"
puts "\e[1A\e[Knew line"

See also Overwrite last line on terminal:

Solution 4:[4]

Following this answer for bash, I've made this method:

def overwrite(text, lines_back = 1)
  erase_lines = "\033[1A\033[0K" * lines_back
  system("echo \"\r#{erase_lines}#{text}\"")
end

which can be used like this:

def print_some_stuff
  print("Only\n")
  sleep(1)
  overwrite("one")
  sleep(1)
  overwrite("line")
  sleep(1)
  overwrite("multiple\nlines")
  sleep(1)
  overwrite("this\ntime", 2)
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user664833
Solution 2 Saloaty
Solution 3 fangxing
Solution 4 Jacquen