class HashMath::Table

The main data structure for a virtual table that can be treated as a key-value builder. Basically, it is a hash with a default 'prototype' assigned to it, which serves as the base record. Then, add is called over and over passing in row_id, field_id, and value, which gives it enough information to pinpoint where to insert the data (memory-wise.) Imagine a two-dimensional table where X is the field_id axis and row is the Y axis. Since it is essentially backed by a hash, the row_id and field_id can be anything that implements hash, eql? and #== properly.

Constants

Row

Attributes

lookup[R]
record[R]

Public Class Methods

new(record) click to toggle source
# File lib/hash_math/table.rb, line 28
def initialize(record)
  raise ArgumentError, 'record is required' unless record

  @lookup = {}
  @record = record

  freeze
end

Public Instance Methods

add(row_id, field_id, value) click to toggle source
# File lib/hash_math/table.rb, line 37
def add(row_id, field_id, value)
  raise KeyOutOfBoundsError, "field_id: #{field_id} not allowed." unless key?(field_id)

  tap { set(row_id, field_id, value) }
end
each() { |row| ... } click to toggle source
# File lib/hash_math/table.rb, line 43
def each
  return enum_for(:each) unless block_given?

  lookup.map do |row_id, fields|
    Row.new(row_id, record.make!(fields)).tap { |row| yield(row) }
  end
end

Private Instance Methods

row(row_id) click to toggle source
# File lib/hash_math/table.rb, line 53
def row(row_id)
  lookup[row_id] ||= {}
end
set(row_id, field_id, value) click to toggle source
# File lib/hash_math/table.rb, line 57
def set(row_id, field_id, value)
  row(row_id)[field_id] = value
end