LoginSignup
26
26

More than 5 years have passed since last update.

進行状況をプログレスバーで表示

Last updated at Posted at 2014-05-08

Homebrewの進行状況、たとえば

$ brew install node.js
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/node-0.10.2
######################################################################## 100.0%

こんな感じのプログレスバー表示を行うメソッドです。

progress_bar メソッド(幅80文字版)

progress_80.rb
#!/usr/bin/env ruby
# coding: utf-8
$stdout.sync = true #書いておかないと出力がバッファに溜め込まれるかも

def progress_bar(i, max = 100)
  i = max if i > max
  rest_size = 1 + 5 + 1      # space + progress_num + %
  bar_width = 79 - rest_size # (width - 1) - rest_size = 72
  percent = i * 100.0 / max
  bar_length = i * bar_width.to_f / max
  bar_str = ('#' * bar_length).ljust(bar_width)
#  bar_str = '%-*s' % [bar_width, ('#' * bar_length)]
  progress_num = '%3.1f' % percent
  print "\r#{bar_str} #{'%5s' % progress_num}%"
end

(0..1000).each do |j|
  sleep 0.001
  progress_bar(j, 1000)
end
puts

実行すると

$ ruby progress_80.rb 
######################################################################## 100.0%

という感じになります。実際に動かして、プログレスバーが伸びていく様子を確認してください。

なお、max を与えないと max = 100 になります。
つまり、i がそのままパーセントを表している場合は引数を一つだけにすることが出来ます。

(0..100).each do |j|
  sleep 0.01
  progress_bar(j)
end
puts

progress_bar メソッド(幅可変版)

(2015/12/23追記)
先ほどの progress_bar メソッドはコンソール幅が80文字決め打ちでしたが、そうじゃない環境だとあまり良くないですよね。コンソール幅は IO.console_size で取得できるのでこれを利用します(冒頭で require 'io/console/size' が必要)。

console_size -> [Integer, Integer] [added by io/console/size]

端末のサイズを [rows, columns] で返します。
io/console が利用できない場合は、IO.default_console_size の値を返します。

require 'io/console/size'
$stdout.sync = true

def progress_bar(i, max = 100)
  height, width = IO.console_size # height は使ってませんが説明のために記載
  i = max if i > max
  rest_size = 1 + 5 + 1 # space + progress_num + %
  bar_width = (width - 1) - rest_size
  percent = i * 100.0 / max
  bar_length = i * bar_width.to_f / max
  bar_str = ('#' * bar_length).ljust(bar_width)
  progress_num = '%3.1f' % percent
  print "\r#{bar_str} #{'%5s' % progress_num}%"
end

(2015/12/23追記ここまで)

rubygems

gemになっているものもいろいろあります。
The Ruby Toolbox - CLI Progress Bars: Indicate the progress of long-running tasks in your command line utilities

なお

この投稿はこちらの二匹目のドジョウですw
CLIでプログレスバーみたいのを出力する - Qiita

ただし、このプログレスバーは以前から個人的に使ってましたw
このスクリプトとかで(出力は若干違いますが
NHK語学講座のラジオ番組ストリーミングを取得するRubyスクリプトgogakuondemand.rb(v3.5 '14/3/31更新版) - 別館 子子子子子子(ねこのここねこ)

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