Created
July 31, 2012 02:23
-
-
Save jpo/3212901 to your computer and use it in GitHub Desktop.
Ruby CLI Progress Indicators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
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
you need to include enumerable at the top (for 1.9.2 and 1.9.3)