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.
Instance Method Summary collapse
- #[](key) ⇒ Object
-
#initialize(original_hash) ⇒ MultiHash
constructor
Initialize an immutable multihash with the provided hash as its source.
Constructor Details
#initialize(original_hash) ⇒ 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.
18 19 20 21 22 23 24 25 |
# File 'lib/multihash/multihash.rb', line 18 def initialize(original_hash) @_hash = Hash.new original_hash.each do |orig_key, value| key_array = orig_key.is_a?(Array) && orig_key || [orig_key] key_array.each { |k| @_hash[k] = value } end end |
Instance Method Details
#[](key) ⇒ Object
27 28 29 |
# File 'lib/multihash/multihash.rb', line 27 def [](key) @_hash[key] end |