class RailwayOperation::Generic::EnsuredAccess
Ensures that the default value is available for use The problem with normal default values is that they are returned, they are not part of the actually collection.
hash = Hash.new { [] } hash == []
However, if you do the following hash << 2 hash == {} hash != 2
With this you can:
ensured_hash = EnsuredAccess({}) { [] } ensured_hash << 2 ensured_hash == { 'a' => 2 }
Public Class Methods
new(obj, default = nil, &block)
click to toggle source
# File lib/railway_operation/generic/ensured_access.rb, line 23 def initialize(obj, default = nil, &block) @obj = obj @default = default || block end
Public Instance Methods
[](key)
click to toggle source
# File lib/railway_operation/generic/ensured_access.rb, line 36 def [](key) @obj[key] ||= @default.respond_to?(:call) ? @default.call : @default @obj[key] end
__getobj__()
click to toggle source
# File lib/railway_operation/generic/ensured_access.rb, line 32 def __getobj__ @obj end
__setobj__(obj)
click to toggle source
# File lib/railway_operation/generic/ensured_access.rb, line 28 def __setobj__(obj) @obj = obj end