Command-line progress indicators
inspired by: http://www.ruby-forum.com/topic/87404
1 2 3 # move cursor to beginning of line 4 cr = "\r" 5 6 7 # ANSI escape code to clear line from cursor to end of line 8 # "\e" is an alternative to "\033" 9 # cf. http://en.wikipedia.org/wiki/ANSI_escape_code 10 11 clear = "\e[0K" 12 13 # reset lines 14 reset = cr + clear 15 16 17 18 #-------------------------------- Example 1 -------------------------------- 19 20 21 (1..100).each do |i| 22 print "#{reset}#{i}%" 23 sleep(0.08) 24 $stdout.flush 25 end 26 27 print "#{reset}" # clear current line 28 29 $stdout.flush 30 puts "done" 31 32 33 34 #-------------------------------- Example 2 -------------------------------- 35 36 37 chars = [ "|", "/", "-", "\\" ] 38 39 # 7 turns on reverse video mode, 31 red , ... 40 n = 31 41 42 str = "#{reset}\e[#{n};1m" 43 44 45 (1..100).each do |i| 46 47 case i 48 when 0..10 then print "#{str}#{chars[0]}" 49 when 10..20 then print "#{str}#{chars[1]}" 50 when 20..30 then print "#{str}#{chars[2]}" 51 when 30..40 then print "#{str}#{chars[3]}" 52 when 40..50 then print "#{str}#{chars[0]}" 53 when 50..60 then print "#{str}#{chars[1]}" 54 when 60..70 then print "#{str}#{chars[2]}" 55 when 70..80 then print "#{str}#{chars[3]}" 56 when 80..90 then print "#{str}#{chars[0]}" 57 when 90..100 then print "#{str}#{chars[1]}" 58 end 59 60 sleep(0.1) 61 $stdout.flush 62 63 end 64 65 print "\e[0m" 66 print "#{reset}" 67 68 $stdout.flush 69 puts "done" 70 71 72 73 #-------------------------------- Example 3 -------------------------------- 74 75 76 MAX = 80 77 78 $stdout.sync = true # alternative to $stdout.flush below 79 80 10.times do 81 foo_string = Time.now.to_s 82 s = foo_string[0..MAX].center(MAX) # or rjust or ljust 83 print cr + s 84 #$stdout.flush 85 sleep(1.1) 86 end 87 88 print "\e[0m" 89 print "#{reset}" 90 91 $stdout.flush 92 puts "done" 93 94