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.



513
514
515
516
# File 'lib/ctioga2/utils.rb', line 513

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

Instance Attribute Details

#hashObject

Hash for non regexp keys



508
509
510
# File 'lib/ctioga2/utils.rb', line 508

def hash
  @hash
end

#regexp_hashObject

Hash for regexp keys



511
512
513
# File 'lib/ctioga2/utils.rb', line 511

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



533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/ctioga2/utils.rb', line 533

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



519
520
521
522
523
524
525
# File 'lib/ctioga2/utils.rb', line 519

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

#keys_for(value) ⇒ Object



546
547
548
549
550
551
552
553
554
# File 'lib/ctioga2/utils.rb', line 546

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