Skip to content

Instantly share code, notes, and snippets.

@quyen91
Forked from jpo/progress_indicators.rb
Created June 3, 2018 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quyen91/770cb4c76d644b65bfc342a275d1f2b4 to your computer and use it in GitHub Desktop.
Save quyen91/770cb4c76d644b65bfc342a275d1f2b4 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment