Class: SafeArray
- Inherits:
-
Object
- Object
- SafeArray
- Defined in:
- lib/universum/safe_array.rb
Class Method Summary collapse
Instance Method Summary collapse
- #[](index) ⇒ Object
- #[]=(index, value) ⇒ Object
-
#initialize ⇒ SafeArray
constructor
A new instance of SafeArray.
- #length ⇒ Object
- #push(item) ⇒ Object
- #size ⇒ Object
Constructor Details
#initialize ⇒ SafeArray
Returns a new instance of SafeArray.
33 34 35 36 |
# File 'lib/universum/safe_array.rb', line 33 def initialize ## todo/check: if array works if value is a (nested/multi-dimensional) array @ary = [] end |
Class Method Details
.build_class(klass_value) ⇒ Object
e.g.
Array.of( Address ), Array.of( Integer), etc.
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/universum/safe_array.rb', line 8 def self.build_class( klass_value ) ## note: care for now only about value type / class ## note: keep a class cache cache = @@cache ||= {} klass = cache[ klass_value ] return klass if klass klass = Class.new( SafeArray ) klass.class_eval( <<RUBY ) def self.klass_value @klass_value ||= #{klass_value} end RUBY ## add to cache for later (re)use cache[ klass_value ] = klass klass end |
.new_zero ⇒ Object
28 |
# File 'lib/universum/safe_array.rb', line 28 def self.new_zero() new; end |
.zero ⇒ Object
29 |
# File 'lib/universum/safe_array.rb', line 29 def self.zero() @zero ||= new_zero; end |
Instance Method Details
#[](index) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/universum/safe_array.rb', line 42 def [](index) item = @ary[ index ] if item.nil? ## todo/check: ## always return (deep) frozen zero object - why? why not? ## let user change the returned zero object - why? why not? if self.class.klass_value.respond_to?( :new_zero ) ## note: use a new unfrozen copy of the zero object ## changes to the object MUST be possible (new "empty" modifable object expected) item = self.class.klass_value.new_zero else # assume value semantics e.g. Integer, Bool, etc. zero values gets replaced ## puts "use value semantics" item = self.class.klass_value.zero end end item end |
#[]=(index, value) ⇒ Object
38 39 40 |
# File 'lib/universum/safe_array.rb', line 38 def []=(index, value) @ary[index] = value end |
#length ⇒ Object
68 |
# File 'lib/universum/safe_array.rb', line 68 def length() size; end |
#push(item) ⇒ Object
60 61 62 63 64 65 |
# File 'lib/universum/safe_array.rb', line 60 def push( item ) ## todo/fix: check if item.is_a? @type ## note: Address might be a String too (Address | String) ## store Address always as String!!! - why? why not? @ary.push( item ) end |
#size ⇒ Object
67 |
# File 'lib/universum/safe_array.rb', line 67 def size() @ary.size; end |