Question

I'm writing a Ruby command line utility and I'd like it to update one line in the console with new data instead of printing multiple lines of output. The effect I'm going for it similar to a console progress bar you might 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 app 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 the output, one word at a time.

$ ruby app.rb
[ this ]
$

Any ideas?

Was it helpful?

Solution

Use \r (carriage return) to move the cursor at the start of the 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

See Demo.

OTHER TIPS

Use print s instead of puts s if you want to print them in the same line.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top