How to get my command line utility to update one line instead of printing multiple lines?

I am writing a Ruby command line utility, and I would like it to update a single line in the console with new data, rather than print multiple lines of output. The effect that I find for him is similar to the console progress bar , you can see when using wget.

For instance:

app.rb

#!/usr/bin/ruby env

data = %w[this is some data]
data.each {|s| puts s}

When I run this application, it will output the following, which spans 4 lines:

$ ruby app.rb
this
is
some
data
$

I would like the area between [] in the following example to show output, one word at a time.

$ ruby app.rb
[ this ]
$

Any ideas?

+3
source share
2 answers

Use \r(carriage return) to move the cursor at the beginning of a line:

data = %w[this is some data]
data.each { |s|
  sleep(0.5)
  print "\r%-20s" % s  # `print` instead of `put` to avoid newline.
  # Additional spaces to overwrite remaining characters of previous output
}
puts

. .

+4

print s puts s, .

0

All Articles