Class: MoreMath::Histogram

Inherits:
Object show all
Defined in:
lib/more_math/histogram.rb

Overview

A histogram gives an overview of a sequence’s elements.

Defined Under Namespace

Classes: Bin

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sequence, arg = 10) ⇒ Histogram

Create a Histogram for the elements of sequence with bins bins.



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/more_math/histogram.rb', line 7

def initialize(sequence, arg = 10)
  @with_counts = false
  if arg.is_a?(Hash)
    bins = arg.fetch(:bins, 10)
    wc = arg[:with_counts] and @with_counts = wc
  else
    bins = arg
  end
  @sequence = sequence
  @bins = bins
  @result = compute
end

Instance Attribute Details

#binsObject (readonly)

Number of bins for this Histogram.



21
22
23
# File 'lib/more_math/histogram.rb', line 21

def bins
  @bins
end

Instance Method Details

#countsObject



32
33
34
# File 'lib/more_math/histogram.rb', line 32

def counts
  each_bin.map(&:count)
end

#display(output = $stdout, width = 50) ⇒ Object

Display this histogram to output, width is the parameter for prepare_display



38
39
40
41
42
43
44
45
# File 'lib/more_math/histogram.rb', line 38

def display(output = $stdout, width = 50)
  width >= 1 or raise ArgumentError, "width needs to be >= 1"
  for r in rows
    output << output_row(r, width)
  end
  output << "max_count=#{max_count}\n"
  self
end

#each_bin(&block) ⇒ Object



28
29
30
# File 'lib/more_math/histogram.rb', line 28

def each_bin(&block)
  @result.each(&block)
end

#max_countObject



47
48
49
# File 'lib/more_math/histogram.rb', line 47

def max_count
  counts.max
end

#to_aObject

Return the computed histogram as an array of Bin objects.



24
25
26
# File 'lib/more_math/histogram.rb', line 24

def to_a
  @result
end