Sha256: d67338d39c36845835c28aca741bf2b251a9aba106cd1ba469c8635fc067d7bf

Contents?: true

Size: 730 Bytes

Versions: 1

Compression:

Stored size: 730 Bytes

Contents

module SimpleTables
  class Table
    attr_reader :data

    def initialize(data,col_names)
      @data=data.map{|r| Record.new(r,col_names)}
    end

    def where(conditions)
      @data.select { |r| r.matches?(conditions) }
    end

    def pivot(rows_col,cols_col,&block)
      result=@data.group_by{|r| [r[cols_col],r[rows_col]]}

      if block_given?
        return PivotTable[result.map{|k,v| [k,block.call(v)] }]
      end

      PivotTable[result.map{|k,v| [k,v.count]}]
    end
  end

  class Record
    def initialize(values,col_names)
      @data=Hash[col_names.zip(values)]
    end

    def [](key)
      @data[key]
    end

    def matches?(conditions)
      conditions.all? { |k,v| self[k] == v }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
simple_tables-0.0.2 lib/simple_tables/table.rb