Class: Factbase::Sum

Inherits:
TermBase show all
Defined in:
lib/factbase/terms/sum.rb

Overview

This class represents a specialized ‘sum’ term. This term calculates the sum of values for a specified key.

Instance Method Summary collapse

Methods included from TermShared

#to_s

Constructor Details

#initialize(operands) ⇒ Sum

Constructor.

Parameters:

  • operands (Array)

    Operands



13
14
15
16
17
# File 'lib/factbase/terms/sum.rb', line 13

def initialize(operands)
  super()
  @operands = operands
  @op = :sum
end

Instance Method Details

#evaluate(_fact, maps, _fb) ⇒ Integer

Evaluate term on a fact.

Parameters:

Returns:

  • (Integer)

    The sum of values for the specified key across all maps



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/factbase/terms/sum.rb', line 24

def evaluate(_fact, maps, _fb)
  k = @operands[0]
  raise "A symbol is expected, but '#{k}' provided" unless k.is_a?(Symbol)
  sum = 0
  maps.each do |m|
    vv = m[k.to_s]
    next if vv.nil?
    vv = [vv] unless vv.respond_to?(:to_a)
    vv.each do |v|
      sum += v
    end
  end
  sum
end