Skip to content

Instantly share code, notes, and snippets.

@kuntoaji
Created September 6, 2013 06:54
Show Gist options
  • Save kuntoaji/6460383 to your computer and use it in GitHub Desktop.
Save kuntoaji/6460383 to your computer and use it in GitHub Desktop.
Simple progress bar script without Gem using Ruby.
#!/usr/bin/env ruby
progress = 'Progress ['
1000.times do |i|
# i is number from 0-999
j = i + 1
# add 1 percent every 10 times
if j % 10 == 0
progress << "="
# move the cursor to the beginning of the line with \r
print "\r"
# puts add \n to the end of string, use print instead
print progress + " #{j / 10} %"
# force the output to appear immediately when using print
# by default when \n is printed to the standard output, the buffer is flushed.
$stdout.flush
sleep 0.05
end
end
puts "\nDone!"
@volb
Copy link

volb commented Jan 8, 2015

Year and a half later I just want to say this was very instructive. I was looking to learn about this but either examples were too vague (stackoverflow) or too complex (various gems). Thank you!

@drewbaumann
Copy link

drewbaumann commented Jul 28, 2016

For anyone that tries this with a number other than 1000 I think that this might make things a little more clear:

progress = 'Progress ['
iteration_count = 1000
iteration_count.times do |i|

# i is number from 0-999
j = i + 1
# how many times the total number is divisible by 100 (I couldn't come up with a great name off the top of my head)
denominator = iteration_count / 100

  # add 1 percent every 10 times
  if j % denominator == 0
    progress << "="
    # move the cursor to the beginning of the line with \r
    print "\r"
    # puts add \n to the end of string, use print instead
    print progress + " #{j / denominator} %]"

    # force the output to appear immediately when using print
    # by default when \n is printed to the standard output, the buffer is flushed. 
    $stdout.flush
    sleep 0.05
  end
end
puts "\nDone!"

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