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

Accepted answer
Score: 81

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

require 'time'

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

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

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

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

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

Score: 1

Here is an example I just wrote up that 6 takes an Array and outputs whitespace if 5 needed. You can uncomment the speed variable 4 to control the speed at runtime. Also remove 3 the other sleep 0.2 The last part in the 2 array must be blank to output the entire 1 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)}
Score: 0

You can use

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

  2. Cursor Movement

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

See also Overwrite last line on terminal:

Score: 0

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 1 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

More Related questions