#!/usr/bin/env ruby # encoding: utf-8 require 'isna' # Percentage bar. # # items = (1..100).to_a # size = (10..100).to_a # length = size.shuffle.first # # items.each do |item| # puts Percentage.new(100, item, length).to_bar # end # class Percentage def initialize(product, divisor, scale = 100) @product = product @scale = scale @pre_percentage = (divisor * @scale / product).to_f @percentage = (@pre_percentage * 100 / @scale) @divisor = divisor end def to_i @percentage.to_i end def to_f @percentage.to_f end # 0 ~ 50 green # 50 ~ 80 yellow # 80 ~ 100 red def to_bar(color = true, bar = '|', label = '') bars = (bar * @pre_percentage.to_f).rjust(@scale, ' ') if color if to_i < 33 bars = bars.to_ansi.green.to_s end if to_i >= 33 and to_i < 66 bars = bars.to_ansi.yellow.to_s end if to_i >= 66 bars = bars.to_ansi.red.to_s end end output_percentage = (to_f.round(2).to_s.rjust(5, ' ') + '%') output_divisor = @divisor.round(2).to_s.rjust(10, ' ') if color output_percentage = output_percentage.to_ansi.pink.to_s output_divisor = output_divisor.to_ansi.cyan.to_s end bindings = { :open => '[', :close => ']', :bars => bars, :percentage => output_percentage, :divisor => output_divisor, :label => label } format("%s%s%s %s %s %