class SavingHash

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 = ::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)

Public Class Methods

new(&b) click to toggle source
# File lib/sup/util.rb, line 696
def initialize &b
  @constructor = b
  @hash = Hash.new
end

Public Instance Methods

[](k) click to toggle source
# File lib/sup/util.rb, line 701
def [] k
  @hash[k] ||= @constructor.call(k)
end