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