Class: Tins::Bijection

Inherits:
Hash show all
Defined in:
lib/tins/bijection.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Hash

#subhash!

Methods included from Subhash

#subhash

Constructor Details

#initialize(inverted = Bijection.new(self)) ⇒ Bijection

Returns a new instance of Bijection.



18
19
20
# File 'lib/tins/bijection.rb', line 18

def initialize(inverted = Bijection.new(self))
  @inverted = inverted
end

Instance Attribute Details

#invertedObject (readonly)

Returns the value of attribute inverted.



44
45
46
# File 'lib/tins/bijection.rb', line 44

def inverted
  @inverted
end

Class Method Details

.[](*pairs) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/tins/bijection.rb', line 3

def self.[](*pairs)
  pairs.size % 2 == 0 or
    raise ArgumentError, "odd number of arguments for #{self}"
  new.fill do |obj|
    (pairs.size / 2).times do |i|
      j = 2 * i
      key = pairs[j]
      value = pairs[j + 1]
      obj.key?(key) and raise ArgumentError, "duplicate key #{key.inspect} for #{self}"
      obj.inverted.key?(value) and raise ArgumentError, "duplicate value #{value.inspect} for #{self}"
      obj[pairs[j]] = pairs[j + 1]
    end
  end
end

Instance Method Details

#[]=(key, value) ⇒ Object



38
39
40
41
42
# File 'lib/tins/bijection.rb', line 38

def []=(key, value)
  key?(key) and return
  super
  @inverted[value] = key
end

#fillObject



22
23
24
25
26
27
28
# File 'lib/tins/bijection.rb', line 22

def fill
  if empty?
    yield self
    freeze
  end
  self
end

#freezeObject



30
31
32
33
34
35
36
# File 'lib/tins/bijection.rb', line 30

def freeze
  r = super
  unless @inverted.frozen?
    @inverted.freeze
  end
  r
end