Veerasundaravel's Ruby on Rails Weblog

January 2, 2008

Print Output like loading indicator

Some time, in ruby programs we may need to print status of the process like loading information below:

1% Percentage completed etc.


Here is the code to print like Loading Information.

Here is the code to print like Loading Information.

# move cursor to beginning of line
cr = "\r"

# ANSI escape code to clear line from cursor to end of line
# "\e" is an alternative to "33"
# cf. http://en.wikipedia.org/wiki/ANSI_escape_code

clear = "\e[0K"

# reset lines
reset = cr + clear

puts "Process Started"
(1..20).each do |i|
print "#{reset}#{i}% Completed"
sleep(0.08)
$stdout.flush
end

print "\n"     # Brings to next line
$stdout.flush

puts "Process Completed"

 

So when you are executing this program, you will get the output something like below:

Process Started

1% Completed

Process Completed
Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: