|
5.7 Code blocks, part twoIn the last chapter, we looked at how code blocks could be used to build conditional expressions, and how you could iterate across all entries in a collection.(27) We built our own code blocks, and handed them off for use by system objects. But there is nothing magic about invoking code blocks; your own code will often need to do so. This chapter will shows some examples of loop construction in Smalltalk, and then demonstrate how you invoke code blocks for yourself.
5.7.1 Integer loopsInteger loops are constructed by telling a number to drive the loop. Try this example to count from 1 to 20:
There's also a way to count up by more than one:
Finally, counting down is done with a negative step:
5.7.2 IntervalsIt is also possible to represent a range of numbers as a standalone object. This allows you to represent a range of numbers as a single object, which can be passed around the system.
As with the integer loops, the Interval class can also represent steps greater than 1. It is done much like it was for our numeric loop above:
5.7.3 Invoking code blocksLet us revisit the checking example and add a method for scanning only checks over a certain amount. This would allow our user to find "big" checks, by passing in a value below which we will not invoke their function. We will invoke their code block with the check number as an argument ment; they can use our existing check: message to get the amount.
The structure of this loop is much like our printChecks message sage from chapter 6. However, in this case we consider each entry, and only invoke the supplied block if the check's value is greater than the specified amount. The line:
invokes the user-supplied block, passing as an argument the
association's key, which is the check number. The
You might find it puzzling that an association takes a
Let's quickly set up a new checking account with $250 (wouldn't this be nice in real life?) and write a couple checks. Then we'll see if our new method does the job correctly:
We will finish this chapter with an alternative way of
writing our
Unlike our previous definition of
Yet, this new behavior can be useful. You can use the same set of tests that we ran above. Notice that our code block:
|