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
# File 'lib/graph/bar.rb', line 46

def mode(mode = nil)
  @mode = mode unless mode.nil?
  @mode
end

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



62
63
64
65
66
67
68
69
70
71
# File 'lib/graph/bar.rb', line 62

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



76
77
78
# File 'lib/graph/bar.rb', line 76

def print_noscale
  print_scale 1
end

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



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

def print_scale(scale = nil)
  scale ||= @scale
  @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



54
55
56
57
# File 'lib/graph/bar.rb', line 54

def scale(scale = nil)
  @scale = scale unless scale.nil?
  @scale
end