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.



178
179
180
181
# File 'lib/ctioga2/utils.rb', line 178

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

Instance Attribute Details

#hashObject

Hash for non regexp keys



173
174
175
# File 'lib/ctioga2/utils.rb', line 173

def hash
  @hash
end

#regexp_hashObject

Hash for regexp keys



176
177
178
# File 'lib/ctioga2/utils.rb', line 176

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



198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/ctioga2/utils.rb', line 198

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



184
185
186
187
188
189
190
# File 'lib/ctioga2/utils.rb', line 184

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

#keys_for(value) ⇒ Object



211
212
213
214
215
216
217
218
219
# File 'lib/ctioga2/utils.rb', line 211

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