Friday, September 6, 2013

Ruby Simple Progress Bar Without Ruby Gems

Simple progress bar script without Gem using Ruby and console.

Gist: https://gist.github.com/kuntoaji/6460383

#!/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!"

2 comments:

  1. Thanks for sharing. I modified yours to work with executing a process in another thread, and print progress while it is executing. Thought I'd share if someone else is looking for a really simple progress indicator.

    -Cory

    t1 = Thread.new{
    system ""
    puts "]"
    puts "Done."
    }

    progress = 'Progress ['

    while t1.status
    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

    # 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.2
    end

    ReplyDelete