Hi Tony,
You stumbled on one of the most powerful features of Smalltalk. The Block (See BlockContext). Blocks are a contextual memory space. They can be passed around and do all sorts of great things that Smalltalk programmers take for granted.
The basic form is [] this is a no argument, no code block. Pretty boring cause it does nothing.
A more advanced form is ['hello'] which is a block with a literal string. Still pretty boring. But at least you can get the string out of the block by aBlock := ['hello']. ^aBlock value.
A bit more advanced: [:arg | 'Hello ', arg] has an argument. Now you can do ^aBlock value: 'Ron'.
You can have more arguments [:arg1 :arg2 | 'Hello ', arg1, ' ', arg2].
Now you can do ^aBlock value: self firstName value: self lastName.
Even more complicated is: | isLoggedIn |
isLoggedIn := true.
[:arg | 'Hello ', arg, ' you are ', (isLoggedIn ifTrue: [''] ifFalse: [' not']), ' logged in']
Now you can do ^aBlock value: 'Ron'. From anywhere and the block remembers the context from where it was created. Pretty cool huh.
The regular select uses a block too:
self select: [:anItem | anItem isBlue]
which uses a do that uses a block
self do: [:anElement | aBlock value: anElement) ifTrue ... ]
Blocks are certainly a good thing to learn.
Happy Coding, Ron Teitelbaum
-----Original Message----- From: beginners-bounces@lists.squeakfoundation.org [mailto:beginners- bounces@lists.squeakfoundation.org] On Behalf Of Tony Giaccone Sent: Tuesday, October 14, 2008 2:12 AM To: beginners@lists.squeakfoundation.org Subject: [Newbies] Total newb...
Ok, so I'm really new to smalltalk. I've done a few basic tutorials and have a simple understanding of the syntax. My pervious programing experience is mostly java/C with a bit of Objective C in the mix.
I'm trying to figure out how to do what seems like a simple thing.
I have a set, I'd like to find out if an object exists in the set.
In a general form. Let's use the a relatively simple case.
Assume I have classes Rock Paper and Scissors.
validHands := Set new. validHands add: Rock new; add Paper new; add Scissors new.
Assume I have a player object which responds to the method throwsAHand with an instance of Rock Paper or Scissors.
how do I craft
validHands contains: aPlayer throwsAHand
I know that contains: takes a block, and that this isn't correctly done.. but I'm trying to get the a handle on how to do this. The intent is to return a boolean, that indicates if the object the player threw is in the Set of valid objects that can be thrown.
Tony
Beginners mailing list Beginners@lists.squeakfoundation.org http://lists.squeakfoundation.org/mailman/listinfo/beginners