ruby 45 lines · 8 steps

Building a terminal progress bar in Ruby

A class that tracks progress and redraws a live bar with percentage and ETA on a single terminal line.

Explained by highlit
1class ProgressBar
2 BAR_WIDTH = 40
3 
4 def initialize(total, io: $stdout)
5 @total = total
6 @current = 0
7 @io = io
8 @start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
9 end
10 
11 def advance(step = 1)
12 @current = [@current + step, @total].min
13 render
14 end
15 
16 def finish
17 @current = @total
18 render
19 @io.print "\n"
20 end
21 
22 private
23 
24 def render
25 fraction = @total.zero? ? 1.0 : @current.to_f / @total
26 filled = (fraction * BAR_WIDTH).round
27 bar = ("█" * filled) + ("░" * (BAR_WIDTH - filled))
28 percent = (fraction * 100).round
29 
30 @io.print format(
31 "\r[%s] %3d%% %d/%d %s",
32 bar, percent, @current, @total, eta(fraction)
33 )
34 @io.flush
35 end
36 
37 def eta(fraction)
38 return "--:--" if fraction.zero?
39 
40 elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - @start
41 remaining = elapsed / fraction - elapsed
42 minutes, seconds = remaining.divmod(60)
43 format("%02d:%02d", minutes, seconds)
44 end
45end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A monotonic clock avoids the pitfalls of wall-clock time when measuring elapsed durations.
  2. 2Printing a carriage return before each frame lets you repaint one terminal line in place.
  3. 3Linear extrapolation from elapsed time and fraction done gives a simple, serviceable ETA.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a terminal progress bar in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code