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

StackOverflow https://stackoverflow.com/questions/21807467

  •  12-10-2022
  •  | 
  •  

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?

有帮助吗?

解决方案

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.

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top