at:tutorial:objects
                Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| at:tutorial:objects [2007/07/18 18:11] – jorge | at:tutorial:objects [2025/06/19 16:09] (current) – Removing uniform access information elisag | ||
|---|---|---|---|
| Line 159: | Line 159: | ||
| def Enumerable := object: { | def Enumerable := object: { | ||
| def collect: closure { | def collect: closure { | ||
| - | def c := self.new(); | + | def c := self.new([]); | 
| self.each: { |v| | self.each: { |v| | ||
| - | closure(v); | + |        | 
| }; | }; | ||
| c; | c; | ||
| Line 168: | Line 168: | ||
| def Array := object: { | def Array := object: { | ||
| def elements := []; | def elements := []; | ||
| + | def init(a) { elements := a; }; | ||
| def add(v) { elements := elements + [v]; self }; | def add(v) { elements := elements + [v]; self }; | ||
| def collect: closure { | def collect: closure { | ||
| Line 173: | Line 174: | ||
| }; | }; | ||
| def each: clo { | def each: clo { | ||
| - |     1.to: elements.length  | + | 1.to: elements.length do: { |i| | 
| - |        | + |       clo(elements[i]); | 
| }; | }; | ||
| }; | }; | ||
| Line 183: | Line 184: | ||
| < | < | ||
| - | > Array.add(1).add(2).add(3) | + | Array.add(1).add(2).add(3) | 
| - | >> < | + | def c := Array.collect: | 
| - | > def c := Array.collect: | + | c.each: { |v| system.print(v)} // prints 234 | 
| - | >> < | + | |
| - | > c.each: { |v| system.println(v)} | + | |
| - | 2 | + | |
| - | 3 | + | |
| - | 4 | + | |
| - | >>nil | + | |
| </ | </ | ||
| Line 234: | Line 229: | ||
| > makeBankAccount(100).balance; | > makeBankAccount(100).balance; | ||
| >> | >> | ||
| - | <object:5068254> | + |   <obj:{super, | 
| </ | </ | ||
| + | |||
| + | This pattern of creating objects by means of " | ||
| + | |||
| + | < | ||
| + | def b := makeBankAccount(100); | ||
| + | def b2 := b.new(); // shares its balance field with b! | ||
| + | b.deposit(10); | ||
| + | </ | ||
| + | |||
| + | In order to prevent this kind of errors, it is considered best practice to override '' | ||
| + | |||
| + | < | ||
| + | def makeBankAccount(balance) { | ||
| + | object: { | ||
| + | def new(@args) { makeBankAccount(@args) }; | ||
| + | def deposit(amnt) { /* as before */ }; | ||
| + | } | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | By overriding '' | ||
| + | |||
at/tutorial/objects.1184775070.txt.gz · Last modified:  (external edit)
                
                