Class: Oinky::ValuesEnumerator

Inherits:
Enumerator
  • Object
show all
Defined in:
lib/oinky/query.rb

Overview

This adds simple operations (max/min/average) to enumerable value sets.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_opt(opt) ⇒ Object

Raises:



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/oinky/query.rb', line 14

def self.from_opt(opt)
  # These are column references.
  if opt.is_a? Symbol
    opt = opt.to_s
  end
  if opt.is_a? String
    # Turn this into a proc that extracts the selected value.
    cn = opt
    opt = lambda {|row| row[cn]}
  end

  raise OinkyException.new("ArgumentError - Invalid proc") unless opt.is_a? Proc
  return opt
end

Instance Method Details

#average(opt) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/oinky/query.rb', line 45

def average(opt)
  avg = nil
  count = 0
  values_loop(opt) { |val|
    if avg
      avg += val
    else
      avg = val
    end
    count += 1
  }
  # We do not test for zero elements.  We just invoke the value's divide
  # method.  The caller can use any type, and define divide however
  # they choose.
  return avg / count
end

#max(opt) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
# File 'lib/oinky/query.rb', line 61

def max(opt)
  mx = nil
  values_loop(opt) { |val|
    if not mx
      mx = val
    elsif mx < val
      mx = val
    end
  }
  return mx
end

#min(opt) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
# File 'lib/oinky/query.rb', line 72

def min(opt)
  mn = nil
  values_loop(opt) { |val|
    if not mn
      mn = val
    elsif mn > val
      mn = val
    end
  }
  return mn
end