Class: SavingHash

Inherits:
Object show all
Defined in:
lib/sup/util.rb

Overview

acts like a hash with an initialization block, but saves any newly-created value even upon lookup.

for example:

class C

attr_accessor :val
def initialize; @val = 0 end

end

h = Hash.new { C.new } h.val # => 0 h.val = 1 h.val # => 0

h2 = SavingHash.new { C.new } h2.val # => 0 h2.val = 1 h2.val # => 1

important note: you REALLY want to use #member? to test existence, because just checking h will always evaluate to true (except for degenerate constructor blocks that return nil or false)

Instance Method Summary collapse

Constructor Details

#initialize(&b) ⇒ SavingHash

Returns a new instance of SavingHash.



622
623
624
625
# File 'lib/sup/util.rb', line 622

def initialize &b
  @constructor = b
  @hash = Hash.new
end

Instance Method Details

#[](k) ⇒ Object



627
628
629
# File 'lib/sup/util.rb', line 627

def [] k
  @hash[k] ||= @constructor.call(k)
end