Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing over previously output lines in the command prompt with ruby

Tags:

I've run command line programs that output a line, and then update that line a moment later. But with ruby I can only seem to output a line and then another line.

What I have being output now:

Downloading file: 11MB 294K/s 12MB 307K/s 14MB 294K/s 15MB 301K/s 16MB 300K/s Done! 

And instead, I want to see this:

Downloading file: 11MB 294K/s 

Followed a moment later by this:

Downloading file: 16MB 300K/s Done! 

The line my ruby script outputs that shows the downloaded filesize and transfer speed would be overwritten each time instead of listing the updated values as a whole new line.

I'm currently using puts to generate output, which clearly isn't designed for this case. Is there a different output method that can achieve this result?

like image 498
Alex Wayne Avatar asked Jan 21 '11 19:01

Alex Wayne


People also ask

How do you print on the same line in ruby?

We can also use "\n" ( newline character ) to print a new line whenever we want as used in most of the programming languages.

How do I run a command line in ruby?

Press Ctrl twice to invoke the Run Anything popup. Type the ruby script. rb command and press Enter . If necessary, you can specify the required command-line options and script arguments.

What is ruby command?

Ruby command is a free and open source programming language; it is flexible and is feature rich. As the name suggests, ruby indeed is a jewel language which comes at a very low entry cost. Its plug and play capability and also easily readable syntax makes it very user-friendly.


1 Answers

Use \r to move the cursor to the beginning of the line. And you should not be using puts as it adds \n, use print instead. Like this:

print "11MB 294K/s" print "\r" print "12MB 307K/s" 

One thing to keep in mind though: \r doesn't delete anything, it just moves the cursor back, so you would need to pad the output with spaces to overwrite the previous output (in case it was longer).

By default when \n is printed to the standard output the buffer is flushed. Now you might need to use STDOUT.flush after print to make sure the text get printed right away.

like image 76
detunized Avatar answered Oct 07 '22 01:10

detunized