Class: CTioga2::RegexpHash

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

Constructor Details

#initializeRegexpHash

Returns a new instance of RegexpHash.



381
382
383
384
# File 'lib/ctioga2/utils.rb', line 381

def initialize()
  @hash = {}
  @regexp_kv = []
end

Instance Attribute Details

#hashObject

Hash for non regexp keys



376
377
378
# File 'lib/ctioga2/utils.rb', line 376

def hash
  @hash
end

#regexp_hashObject

Hash for regexp keys



379
380
381
# File 'lib/ctioga2/utils.rb', line 379

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



401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/ctioga2/utils.rb', line 401

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



387
388
389
390
391
392
393
# File 'lib/ctioga2/utils.rb', line 387

def []=(key, value)
  if Regexp === key
    @regexp_kv <<  [key, value]
  else
    @hash[key] = value
  end
end

#keys_for(value) ⇒ Object



414
415
416
417
418
419
420
421
422
# File 'lib/ctioga2/utils.rb', line 414

def keys_for(value)
  ret = []
  for k,v in @hash
    if value == v
      ret << k
    end
  end
  return ret
end