Class: EPC::VerticalBar

Inherits:
Object show all
Defined in:
lib/epc/vertical_bar.rb

Constant Summary collapse

WIDTH =
80
HEIGHT =
16

Instance Method Summary collapse

Constructor Details

#initialize(array) ⇒ VerticalBar

Returns a new instance of VerticalBar.



8
9
10
# File 'lib/epc/vertical_bar.rb', line 8

def initialize(array)
  @values = array
end

Instance Method Details



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/epc/vertical_bar.rb', line 12

def print
  content = ""
  return result unless @values && !@values.empty?

  # adjust X axis for WIDTH cols
  if @values.length > WIDTH
    old_values = @values
    @values = []
    0.upto(WIDTH - 1) {|i| @values << old_values[i * old_values.length / WIDTH]}
  end
  min = @values.inject {|min,ea| ea.nil? ? min : (min < ea ? min : ea)} # can't use @values.min - may contain nils
  max = @values.inject {|max,ea| ea.nil? ? max : (max > ea ? max : ea)} # can't use @values.max - may contain nils
  spread = [max - min, 1].max

  display = Array.new(HEIGHT).collect { Array.new(WIDTH, ' ') } # initialize display with blanks
  @values.each_with_index do |e, i|
    if e
      num = (e - min) * HEIGHT / spread
      (HEIGHT - 1).downto(HEIGHT - 1 - num) {|j| display[j][i] = '^'}
    else
      display[HEIGHT - 1][i] = '_'
    end
  end
  display.each {|ar| ar.each {|e| content << e}; content << "\n"}
  content
end