Class: Namo

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/Namo/Row.rb,
lib/namo.rb,
lib/Namo/VERSION.rb,
lib/Namo/NegatedDimension.rb

Overview

Namo/NegatedDimension.rb Namo::NegatedDimension

Defined Under Namespace

Classes: NegatedDimension, Row

Constant Summary collapse

VERSION =
'0.4.0'

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#dataObject

Returns the value of attribute data.



11
12
13
# File 'lib/namo.rb', line 11

def data
  @data
end

#formulaeObject

Returns the value of attribute formulae.



12
13
14
# File 'lib/namo.rb', line 12

def formulae
  @formulae
end

Instance Method Details

#+(other) ⇒ Object



59
60
61
62
63
64
# File 'lib/namo.rb', line 59

def +(other)
  unless dimensions == other.dimensions
    raise ArgumentError, "dimensions do not match"
  end
  self.class.new(@data + other.data, formulae: other.formulae.merge(@formulae))
end

#-(other) ⇒ Object



66
67
68
69
70
71
# File 'lib/namo.rb', line 66

def -(other)
  unless dimensions == other.dimensions
    raise ArgumentError, "dimensions do not match"
  end
  self.class.new(@data - other.data, formulae: @formulae.dup)
end

#[](*names, **selections) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/namo.rb', line 26

def [](*names, **selections)
  rows = selections.any? ? select{|row| row.match?(selections)} : entries
  negated, positive = names.partition{|n| n.is_a?(NegatedDimension)}
  if negated.any? && positive.any?
    raise ArgumentError, "cannot mix projection and contraction in a single call"
  end
  projected = (
    if negated.any?
      excluded = negated.map(&:name)
      kept = dimensions - excluded
      rows.map do |row|
        kept.each_with_object({}){|name, hash| hash[name] = row[name]}
      end
    elsif positive.any?
      rows.map do |row|
        positive.each_with_object({}){|name, hash| hash[name] = row[name]}
      end
    else
      rows.map(&:to_h)
    end
  )
  self.class.new(projected, formulae: @formulae.dup)
end

#[]=(name, proc) ⇒ Object



50
51
52
# File 'lib/namo.rb', line 50

def []=(name, proc)
  @formulae[name] = proc
end

#coordinatesObject



18
19
20
21
22
23
24
# File 'lib/namo.rb', line 18

def coordinates
  @coordinates ||= (
    dimensions.each_with_object({}) do |dimension, hash|
      hash[dimension] = @data.map{|row| row[dimension]}.uniq
    end
  )
end

#dimensionsObject



14
15
16
# File 'lib/namo.rb', line 14

def dimensions
  @dimensions ||= @data.first.keys
end

#each(&block) ⇒ Object



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

def each(&block)
  return enum_for(:each) unless block_given?
  @data.each{|row_data| block.call(Row.new(row_data, @formulae))}
end

#to_aObject



73
74
75
76
77
78
79
# File 'lib/namo.rb', line 73

def to_a
  @data.map do |row|
    row.keys.each_with_object({}) do |key, hash|
      hash[key] = row[key]
    end
  end
end