Class: CombinationHash

Inherits:
Object
  • Object
show all
Defined in:
lib/combination_hash.rb

Instance Method Summary collapse

Constructor Details

#initialize(opt = {}) ⇒ CombinationHash

Returns a new instance of CombinationHash.



4
5
6
7
8
9
# File 'lib/combination_hash.rb', line 4

def initialize(opt={})
  @data = {}
  opt.each do |k,v|
    self[*k] = v
  end
end

Instance Method Details

#[](*args) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/combination_hash.rb', line 11

def [](*args)
  h = @data
  args.sort.each_with_index do |a,i|
    if args[i + 1].nil?
      return h[a]
    else
      if h[a].nil?
        return nil
      else
        h = h[a]
        return nil unless h.kind_of?(Hash)
      end
    end
  end
  nil
end

#[]=(*args) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/combination_hash.rb', line 28

def []=(*args)
  val = args.pop
  h = @data
  args.sort.each_with_index do |a,i|
    h[a] ||= {}
    if args[i + 1].nil?
      h[a] = val
    else
      h = h[a]
    end
  end
end