here's a version of a ruby/smalltalk-like each in rebol: in smalltalk you can write: collectionObject each: [:thing | thing printName ] ruby used the same idea etc - a code block is passed to an object here's a rebol version collection: make object! [ data: copy [] each: func [blk [block!] /local iterator statement ][ iterator: to word! first blk statement: copy skip blk 1 foreach item data [ set iterator item do bind statement iterator ] ] ] This works by taking an input block of the form : [ :x print x ] or [ :num add total num ] etc iterator: to word! first blk just sets up iterator to be a work like a or x ( not a get-word like :a or :x ) I use a get-word just as a smalltalkish reminder that this is a dummy variable ( [ a print a] would work too) statement: copy skip blk 1 just makes a copy of the rest of input block ie statement would be [print x] say , i suppose chopping off the first would work too.. within the loop we set the value of this word ( say x) to successive items in the internal datablock, so the word we indirectly talking about has a different value each time round. do bind statement iterator interprets the statement using the current value of the word and do executes it. people: make collection [ data: ["fred" "george" "mary" "jane"] ] people/each [:person print rejoin ["Hello " person]] Hello fred Hello george Hello mary Hello jane >> I guess there might be probs if the "dummy" variable was also a word used internally by the object containing the each method .
You need to create an account or log in to post comments to this site.