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 =
%w{[] assoc default 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.
30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/multihash/multihash.rb', line 30 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
.[](args) ⇒ Object
69 70 71 |
# File 'lib/multihash/multihash.rb', line 69 def self.[](args) MultiHash.new(Hash[args]) end |
Instance Method Details
#grouped ⇒ Object
45 46 47 |
# File 'lib/multihash/multihash.rb', line 45 def grouped Hash[@_groups.values.map { |g| [g, self[g.first]] }] end |
#set(key, value) ⇒ Object Also known as: []=
49 50 51 52 53 |
# File 'lib/multihash/multihash.rb', line 49 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
56 57 58 59 |
# File 'lib/multihash/multihash.rb', line 56 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
61 62 63 |
# File 'lib/multihash/multihash.rb', line 61 def to_h @_hash end |
#values ⇒ Object
65 66 67 |
# File 'lib/multihash/multihash.rb', line 65 def values @_values ||= @_hash.values.uniq end |