ComputerProgrammingwithGNUSmalltalk:4.2

From 흡혈양파의 번역工房
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

선택 제어

ifTrue:

첫 선택 제어 메시지는 ifTrue: 입니다. 일반적인 구조는 다음과 같습니다.

anObject ifTrue: [block-expression-1. block-expression-2]


Boolean 객체에 이 메시지가 전달되면, 객체가 true 일 때, 코드 블록 내의 표현을 실행하며, false일 때에는 무시합니다. 예를 들어보겠습니다.

| ourVariable |

ourVariable := true.

ourVariable ifTrue: [
	'Our variable is true.' printNl.
]


'Our variable is true.'


ourVariable이라고 부르는 변수를 생성하고, true 객체를 지정합니다. 그 다음 ifTrue: 메시지를 보냅니다. ourVariable이 true로 지정되어 있기 때문에, 코드블록을 수행합니다.


질문:
ourVariable을 false 객체로 할당하고 같은 코드를 수행하여 보십시오.


ifFalse:

ifFalse: 메시지는 그것이 false 객체에게 보내졌을 때 코드 블록을 수행하는 것을 제외하면 ifTrue:와 같습니다.


ifTrue:ifFalse:

이제 여러분의 객체가 참일 때 수행할 코드와 거짓일 때 수행할 코드에 대해 써 볼 시간입니다. 이 메시지는 여러분들에게 쉬운 방법을 제공합니다. 일반 구조를 보면 다음과 같습니다.

anObject ifTrue: [block-expression-1. block-expression-2] ifFalse: [block-expression-3. block-expression-4]


물론 더욱 보기 좋게 다음과 같이 쓴다고 하여도 문제 없습니다.

an-object
	ifTrue: [
		the-code-block-to-execute
	] ifFalse: [
		the-code-block-to-execute
	]

이제 ifTrue:ifFalse: 메시지를 사용하는 예를 하나 들어서 선택 제어 메시지를 끝낼까 합니다.

| ourVariable |

ourVariable := false.

ourVariable ifTrue: [
	'Our variable is true.' printNl.
] ifFalse: [
	'Our variable is false.' printNl.
]
'Our variable is false.'

Notes