LoginSignup
4
4

More than 5 years have passed since last update.

Rubyにて標準出力で表示するプログレスバーなどを作る

Last updated at Posted at 2016-11-03

やりたいのは以下のように更新されていく標準出力を作ること

sample.gif

コツはprint "\r"。これをするとカーソル位置が行頭に戻り、一つの行を上書きしていくことができる。

話はこれで終わりなのだけどこれだけじゃつまらないので、これを使ったお遊びを2つ書きました。

プログレスバーっぽいものを表示する

def progress_bar
  num = rand(20)
  1.upto(num) do |i|
    print "\r#{'=' * i}>"
    sleep 0.2
    puts " End" if i == num
  end
end

progress_bar.gif

おみくじ

def omikuji
  kuji = %w(大吉 中吉 吉 末吉 凶 大凶)
  num = rand(30)
  0.upto(num) do |i|
    print "\r#{kuji.shuffle[i % kuji.size]}"
    sleep 0.1
  end
end

omikuji.gif

4
4
0

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
4
4