Skip to content

Instantly share code, notes, and snippets.

@jpo
Created July 31, 2012 02:23
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jpo/3212901 to your computer and use it in GitHub Desktop.
Save jpo/3212901 to your computer and use it in GitHub Desktop.
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
Copy link

hamin commented Aug 1, 2012

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

include Enumerable
#....

@jpo
Copy link
Author

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