Class: MultiKeyHash
- Inherits:
-
Object
- Object
- MultiKeyHash
- Defined in:
- lib/multi_key_hash.rb,
lib/multi_key_hash/version.rb
Constant Summary collapse
- VERSION =
'0.1.2'
Instance Method Summary collapse
- #[](outer_key) ⇒ Object
- #[]=(outer_key, new_value) ⇒ Object
- #delete(key) ⇒ Object
-
#initialize(values = nil) ⇒ MultiKeyHash
constructor
A new instance of MultiKeyHash.
- #to_h ⇒ Object
Constructor Details
#initialize(values = nil) ⇒ MultiKeyHash
Returns a new instance of MultiKeyHash.
5 6 7 8 9 |
# File 'lib/multi_key_hash.rb', line 5 def initialize(values = nil) @next_key = 1 @outer = @inner = {} order_values(values) end |
Instance Method Details
#[](outer_key) ⇒ Object
11 12 13 |
# File 'lib/multi_key_hash.rb', line 11 def [](outer_key) @outer[outer_key].nil? ? nil : @inner[@outer[outer_key]] end |
#[]=(outer_key, new_value) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/multi_key_hash.rb', line 15 def []=(outer_key, new_value) if outer_key.is_a?(Array) && !outer_key.empty? order_values(outer_key, new_value) else inner_key = @inner.select do |_, existing| existing == new_value end.map do |key, _| key end.first if inner_key @outer[outer_key] = inner_key else remove_hex_key(outer_key) uniq_key = generate_uniq @outer[outer_key] = uniq_key @inner[uniq_key] = new_value @next_key += 1 end end end |
#delete(key) ⇒ Object
50 51 52 53 |
# File 'lib/multi_key_hash.rb', line 50 def delete(key) remove_hex_key(key) delete_key(key) end |
#to_h ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/multi_key_hash.rb', line 37 def to_h converted = {} @inner.each do |i_key, i_value| @outer.each do |o_key, o_value| if i_value == o_key converted[i_key] = o_value end end end converted end |