Class: Labelizer::Container
- Inherits:
-
Object
- Object
- Labelizer::Container
- Includes:
- Enumerable
- Defined in:
- lib/labelizer/container.rb
Instance Method Summary collapse
- #[](key) ⇒ Object
- #each ⇒ Object
-
#initialize(keys, &block) ⇒ Container
constructor
A new instance of Container.
Constructor Details
#initialize(keys, &block) ⇒ Container
Returns a new instance of Container.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/labelizer/container.rb', line 5 def initialize(keys,&block) case keys when Hash @keys = keys.keys @values = keys.values @map = keys.invert else @keys = keys @values = [] @map = {} end @hash = Hash.new(&block) normalized_keys = @keys self.singleton_class.class_eval do normalized_keys.each do |key| define_method key do @hash[key] end end end end |
Instance Method Details
#[](key) ⇒ Object
28 29 30 31 32 |
# File 'lib/labelizer/container.rb', line 28 def [](key) return @hash[key] if @keys.include?(key) return @hash[@map[key]] if @values.include?(key) raise KeyError, "key: #{key.inspect} not found" end |
#each ⇒ Object
34 35 36 37 38 |
# File 'lib/labelizer/container.rb', line 34 def each @keys.each do |key| yield key, @hash[key] end end |