Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Ruby CLI Progress Indicators
# Terminal Progress Indicators. Four examples are included: percentage,
# spinner, progress bar, and combined. This script has been tested on
# Mac OS X 10.8 with Ruby 1.8.7, 1.9.1, 1.9.2, and 1.9.3
class Spinner
include Enumerable
def each
loop do
yield '|'
yield '/'
yield '-'
yield '\\'
end
end
end
spinner = Spinner.new.enum_for(:each)
$stdout.sync = true
# Example 1: percentage
1.upto(100) do |i|
printf("\rPercentage: %d%", i)
sleep(0.05)
end
puts
# Example 2: spinner
1.upto(100) do |i|
printf("\rSpinner: %s", spinner.next)
sleep(0.05)
end
puts
# Example 3: progress bar
0.step(100, 5) do |i|
printf("\rProgress Bar: [%-20s]", "=" * (i/5).floor)
sleep(0.05)
end
puts
# Example 4: combined
1.upto(100) do |i|
printf("\rCombined: [%-20s] %d%% %s", "=" * (i/5).floor, i, spinner.next)
sleep(0.05)
end
puts

hamin commented Aug 1, 2012

you need to include enumerable at the top (for 1.9.2 and 1.9.3)

include Enumerable
#....
Owner

jpo commented Aug 2, 2012

I've updated the gist so that it works with Ruby 1.8.7, 1.9.1, 1.9.2, and 1.9.3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment