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

后端 未结 3 1779
北荒
北荒 2020-12-13 17:23

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 stackin

相关标签:
3条回答
  • 2020-12-13 18:13

    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
    
    0 讨论(0)
  • 2020-12-13 18:14

    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!

    0 讨论(0)
  • 2020-12-13 18:17

    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)}
    
    0 讨论(0)
提交回复
热议问题