1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Rubyでコンソールにプログレスバーを作ってみた

Last updated at Posted at 2022-02-01

:cherries: できたもの

ezgif-5-7e2ac60638.gif

:book: プログラム

print "\r"
で、カーソルをコンソールの行頭に移動させて、一行分上書きできる。

"\e[32m#{str}\e[0m"
で、任意の文字 str を緑色で表示させる。

sym = [
  '\\',
  '|',
  '/',
  '-'
]

def green(str)
  "\e[32m#{str}\e[0m"
end

1.upto(100) do |i|
  print "\r"
  print " (#{sym[i % sym.length]}) ["
  print ('/' * (i / 10)).ljust(10, ' ') << ']'
  sleep 0.03
end

8.times do |i|
  print "\r"
  print ' (o) [ '
  print green('ALL DONE'[0, i + 1].ljust(8, '.'))
  print ' ]'
  sleep 0.1
end


:mag: 参考

https://stackoverflow.com/questions/1489183/how-can-i-use-ruby-to-colorize-the-text-output-to-a-terminal
https://stackoverflow.com/questions/31090782/how-to-overwrite-the-current-console-line-after-gets-in-ruby
https://ezgif.com/video-to-gif

1
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?