Blocks - the Friends of Conditionals and Loops

Damien Cassou, Stéphane Ducasse and Luc Fabresse http://stephane.ducasse.free.fr

Remember: A Block Definition Freezes its Body

[ 2 + 6 ] 
> [ 2 + 6 ] 

Remember: Block Execution

[ 2 + 6 ] value
> 8 
| b |
b := [ 2 + 6 ].
b value.
> 8
b value
> 8 

Blocks are Used to Express Conditions

max: anObject 
  "Answer the receiver or the argument, whichever has the greater anObject."

  ^ self > anObject
      ifTrue: [ self ]
      ifFalse: [ anObject ]

Yes this is a message ifTrue:ifFalse: sent to a Boolean

Blocks are Used to Express Loops

10 timesRepeat: [ File stdout << '.' ]
> ............

Blocks are Used to Express Loops (2)

1 to: 10 do: [:i | File stdout << i ]
> 12345678910 

Blocks are Used to Express Loops (3)

1 to: 100 by: 3 do: [:i | File stdout << i ]
> 147101316192225283134374043464952555861646
> 770737679828588919497100

Blocks are Used For Iterators

#(2 4 5 -4 3 -2) collect: [ :each | each abs ]
> #(2 4 5 4 3 2)

Yes ifTrue:ifFalse: is a message!

Weather isRaining
    ifTrue: [ self takeMyUmbrella ]
    ifFalse: [ self takeMySunglasses ]

Implementation Note

Summary

/