Sha256: 44975729b469bc31113ff8f2b13f86975200115a799f6b63c93fdb89fd3994c5

Contents?: true

Size: 925 Bytes

Versions: 11

Compression:

Stored size: 925 Bytes

Contents

module Datasets
  class Dictionary
    include Enumerable

    def initialize(values)
      build_dictionary(values)
    end

    def id(value)
      @value_to_id[value]
    end

    def value(id)
      @id_to_value[id]
    end

    def ids
      @id_to_value.keys
    end

    def values
      @id_to_value.values
    end

    def each(&block)
      @id_to_value.each(&block)
    end

    def size
      @id_to_value.size
    end
    alias_method :length, :size

    def encode(values)
      values.collect do |value|
        id(value)
      end
    end

    def decode(ids)
      ids.collect do |id|
        value(id)
      end
    end

    private
    def build_dictionary(values)
      @id_to_value = {}
      @value_to_id = {}
      id = 0
      values.each do |value|
        next if @value_to_id.key?(value)
        @id_to_value[id] = value
        @value_to_id[value] = id
        id += 1
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
red-datasets-0.1.7 lib/datasets/dictionary.rb
red-datasets-0.1.6 lib/datasets/dictionary.rb
red-datasets-0.1.5 lib/datasets/dictionary.rb
red-datasets-0.1.4 lib/datasets/dictionary.rb
red-datasets-0.1.3 lib/datasets/dictionary.rb
red-datasets-0.1.2 lib/datasets/dictionary.rb
red-datasets-0.1.1 lib/datasets/dictionary.rb
red-datasets-0.1.0 lib/datasets/dictionary.rb
red-datasets-0.0.9 lib/datasets/dictionary.rb
red-datasets-0.0.8 lib/datasets/dictionary.rb
red-datasets-0.0.7 lib/datasets/dictionary.rb