Class: MultiHash
- Inherits:
-
Object
- Object
- MultiHash
- Defined in:
- lib/multihash/multihash.rb
Overview
This class provides a very simple interface for a hash with multiple keys that reference the same value. This is convenient for lookup tables that have several mappings to a single value, without doing anything particularly gross with Array#include? lookups.
Constant Summary collapse
- HASH_METHOD_WHITELIST =
[ :[], :assoc, :default, :empty?, :each, :each_key, :each_pair, :each_value, :fetch, :keys, :select, :values_at ]
Instance Attribute Summary collapse
-
#immutable ⇒ Object
(also: #immutable?)
Returns the value of attribute immutable.
Class Method Summary collapse
Instance Method Summary collapse
- #grouped ⇒ Object
-
#initialize(original_hash = {}, immutable = true) ⇒ MultiHash
constructor
Initialize an immutable multihash with the provided hash as its source.
- #set(key, value) ⇒ Object (also: #[]=)
- #set_group(key, value) ⇒ Object
- #to_h ⇒ Object
- #values ⇒ Object
Constructor Details
#initialize(original_hash = {}, immutable = true) ⇒ MultiHash
Initialize an immutable multihash with the provided hash as its source. For example, we might want to look up the nation which produces different types of cars:
MultiHash.new (
%w{Honda Nissan} => :japan,
%w{Ford Chrysler} => :us,
'BMW' => :germany
)
a multihash, with arrays or single objects as keys.
42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/multihash/multihash.rb', line 42 def initialize(original_hash={}, immutable=true) @_hash = Hash.new(original_hash.default) @immutable = immutable groups = [] original_hash.each do |orig_key, value| key_array = orig_key.is_a?(Array) && orig_key || [orig_key] groups << key_array key_array.each { |k| map_value(k, value) } end store_groups(groups) unless immutable? end |
Instance Attribute Details
#immutable ⇒ Object Also known as: immutable?
Returns the value of attribute immutable.
6 7 8 |
# File 'lib/multihash/multihash.rb', line 6 def immutable @immutable end |
Class Method Details
Instance Method Details
#grouped ⇒ Object
57 58 59 |
# File 'lib/multihash/multihash.rb', line 57 def grouped Hash[@_groups.values.map { |g| [g, self[g.first]] }] end |
#set(key, value) ⇒ Object Also known as: []=
61 62 63 64 65 |
# File 'lib/multihash/multihash.rb', line 61 def set(key, value) fail 'Cannot modify an immutable MultiHash!' if immutable? split_key_from_group(key) map_value(key, value) end |
#set_group(key, value) ⇒ Object
68 69 70 71 |
# File 'lib/multihash/multihash.rb', line 68 def set_group(key, value) fail 'Cannot modify an immutable MultiHash!' if immutable? @_groups[key].each { |k| map_value(k, value) } end |
#to_h ⇒ Object
73 74 75 |
# File 'lib/multihash/multihash.rb', line 73 def to_h @_hash end |
#values ⇒ Object
77 78 79 |
# File 'lib/multihash/multihash.rb', line 77 def values @_values ||= @_hash.values.uniq end |