Class: Graph::Bar

Inherits:
Object
  • Object
show all
Defined in:
lib/graph/bar.rb

Overview

This class allows the display of data arrays in bar graph format

Instance Method Summary collapse

Constructor Details

#initialize(data = nil) ⇒ Bar

Allows optionally setting the initial dataset as a parameter



25
26
27
28
29
# File 'lib/graph/bar.rb', line 25

def initialize(data = nil)
  data(data)
  mode(PrintMode::NOSCALE)
  scale(1)
end

Instance Method Details

#data(data = nil) ⇒ Object

Get or Set the data array



34
35
36
37
38
39
40
41
# File 'lib/graph/bar.rb', line 34

def data(data = nil)
  unless data.nil?
    raise ArgumentError, 'Data Must Be Enumerable!', caller unless
      data.is_a? Enumerable
    @data = data
  end
  @data
end

#mode(mode = nil) ⇒ Object

Get or Set the print mode



46
47
48
49
50
51
52
53
# File 'lib/graph/bar.rb', line 46

def mode(mode = nil)
  unless mode.nil?
    raise ArgumentError, 'Invalid Print Mode!', caller unless
      [PrintMode::SCALE, PrintMode::NOSCALE].include? mode
    @mode = mode
  end
  @mode
end

Print the graph to stdout, based on the print mode & scale



70
71
72
73
74
75
76
77
78
79
# File 'lib/graph/bar.rb', line 70

def print(mode = nil)
  case mode || @mode
  when PrintMode::NOSCALE
    print_noscale
  when PrintMode::SCALE
    print_scale
  else
    raise ArgumentError, 'Invalid Print Mode', caller
  end
end

Print the graph without any scaling



84
85
86
# File 'lib/graph/bar.rb', line 84

def print_noscale
  print_scale 1
end

Prints graph with a scale. Scale of 10 means every 10 values is displayed as 1 character

Raises:

  • (ArgumentError)


92
93
94
95
96
97
98
# File 'lib/graph/bar.rb', line 92

def print_scale(scale = nil)
  scale ||= @scale
  raise ArgumentError, 'Invalid Scale', caller unless scale > 0
  @data.each_with_index do |count, index|
    printf "%02d|%s\n", index, ('#' * (count / scale))
  end
end

#scale(scale = nil) ⇒ Object

Get or Set th print scale



58
59
60
61
62
63
64
65
# File 'lib/graph/bar.rb', line 58

def scale(scale = nil)
  unless scale.nil?
    raise ArgumentError, 'Invalid Scale!', caller unless
      scale > 0
    @scale = scale
  end
  @scale
end