Class: CTioga2::RegexpHash
- Inherits:
-
Object
- Object
- CTioga2::RegexpHash
- Defined in:
- lib/ctioga2/utils.rb
Overview
This class implements a Hash whose values can also be retrieved by pattern matching.
Instance Attribute Summary collapse
-
#hash ⇒ Object
Hash for non regexp keys.
-
#regexp_hash ⇒ Object
Hash for regexp keys.
Instance Method Summary collapse
-
#[](key) ⇒ Object
Gets the value corresponding to the key, using pattern matching should the need arise.
-
#[]=(key, value) ⇒ Object
Sets the key to the given value.
-
#initialize ⇒ RegexpHash
constructor
A new instance of RegexpHash.
- #keys_for(value) ⇒ Object
Constructor Details
#initialize ⇒ RegexpHash
Returns a new instance of RegexpHash.
366 367 368 369 |
# File 'lib/ctioga2/utils.rb', line 366 def initialize() @hash = {} @regexp_kv = [] end |
Instance Attribute Details
#hash ⇒ Object
Hash for non regexp keys
361 362 363 |
# File 'lib/ctioga2/utils.rb', line 361 def hash @hash end |
#regexp_hash ⇒ Object
Hash for regexp keys
364 365 366 |
# File 'lib/ctioga2/utils.rb', line 364 def regexp_hash @regexp_hash end |
Instance Method Details
#[](key) ⇒ Object
Gets the value corresponding to the key, using pattern matching should the need arise.
If there are several regexps matching a given key, the implementation guarantees that the last one to have been inserted that matches is taken
386 387 388 389 390 391 392 393 394 395 396 397 |
# File 'lib/ctioga2/utils.rb', line 386 def [](key) if @hash.key?(key) return @hash[key] else for k,v in @regexp_kv.reverse if k === key return v end end end return nil end |
#[]=(key, value) ⇒ Object
Sets the key to the given value
372 373 374 375 376 377 378 |
# File 'lib/ctioga2/utils.rb', line 372 def []=(key, value) if Regexp === key @regexp_kv << [key, value] else @hash[key] = value end end |
#keys_for(value) ⇒ Object
399 400 401 402 403 404 405 406 407 |
# File 'lib/ctioga2/utils.rb', line 399 def keys_for(value) ret = [] for k,v in @hash if value == v ret << k end end return ret end |