Class: Tins::Bijection
Overview
A hash subclass that ensures bijection between keys and values
Instance Attribute Summary collapse
-
#inverted ⇒ Bijection
readonly
The inverted attribute returns the inverted state of the object.
Class Method Summary collapse
-
.[](*pairs) ⇒ Bijection
Creates a new Bijection instance with key-value pairs.
Instance Method Summary collapse
-
#[]=(key, value) ⇒ Object
The []= method assigns a value to a key in the hash and maintains an inverted index.
-
#fill {|self| ... } ⇒ self
The fill method populates the object with content from a block if it is empty.
-
#freeze ⇒ Object
The freeze method freezes the current object and its inverted attribute.
-
#initialize(inverted = Bijection.new(self)) ⇒ Bijection
constructor
The initialize method sets up a new instance with an inverted bijection.
Methods inherited from Hash
Methods included from Subhash
Constructor Details
Instance Attribute Details
#inverted ⇒ Bijection (readonly)
The inverted attribute returns the inverted state of the object. Creates a new Bijection instance filled with key-value pairs.
78 79 80 |
# File 'lib/tins/bijection.rb', line 78 def inverted @inverted end |
Class Method Details
.[](*pairs) ⇒ Bijection
Creates a new Bijection instance with key-value pairs.
bijection
10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/tins/bijection.rb', line 10 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
This method will not overwrite existing keys, it will return early
The []= method assigns a value to a key in the hash and maintains an inverted index.
if the key already exists.
68 69 70 71 72 |
# File 'lib/tins/bijection.rb', line 68 def []=(key, value) key?(key) and return super @inverted[value] = key end |
#fill {|self| ... } ⇒ self
The fill method populates the object with content from a block if it is empty.
empty
39 40 41 42 43 44 45 |
# File 'lib/tins/bijection.rb', line 39 def fill if empty? yield self freeze end self end |
#freeze ⇒ Object
The freeze method freezes the current object and its inverted attribute.
50 51 52 53 54 55 56 |
# File 'lib/tins/bijection.rb', line 50 def freeze r = super unless @inverted.frozen? @inverted.freeze end r end |