이 글은 Canol Gokel님이 만든 Computer Programming using GNU Smalltalk를 읽고 정리한 것이다.
블록 blocks은 나중에 사용하기 위해서 표현식들을 모아놓은 객체이다.
아래와 같이 대괄호로 감싼다.
['Hello World!' printNl.
(3 + 7) printNl]
중요한 점은 블록도 객체라는 것이다.
블록은 생성했을 때 바로 실행되지는 않는다.
블록을 실행하려면 메세지 value
를 보내야 한다.
['Hello World!' printNl.
(3 + 7) printNl] value
블록에는 인자 argument를 넣을 수 있다.
[:blockArgument1 :blockArgument2 | block-expression-1. block-expression-2]
블록 안에는 블록 인자를 먼저 적는데 블록 인자 앞에는 콜론을 적는다.
블록 인자와 블록의 메인이 되는 표현식은 파이프 |
로 구분한다.
"blocks.st"
"A program which involves a block with an argument."
| greetings |
greetings := [:platesOfCornFlakes | 'I have eaten ', platesOfCornFlakes
printString, ' plates of corn flakes this morning!'].
('Hello ma! ', (greetings value: 3)) printNl.
$ gst blocks.st
'Hello ma! I have eaten 3 plates of corn flakes this morning!'
블록 인자를 블록 표현식에 적을 때는 콜론을 적지 않는다.