Class: SavingHash
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
- #[](k) ⇒ Object
-
#initialize(&b) ⇒ SavingHash
constructor
A new instance of SavingHash.
Constructor Details
#initialize(&b) ⇒ SavingHash
Returns a new instance of SavingHash.
611 612 613 614 |
# File 'lib/sup/util.rb', line 611 def initialize &b @constructor = b @hash = Hash.new end |
Instance Method Details
#[](k) ⇒ Object
616 617 618 |
# File 'lib/sup/util.rb', line 616 def [] k @hash[k] ||= @constructor.call(k) end |