Home Segments Index Top Previous Next

151: Mainline

You can embed a conditional expression inside another conditional expression. Yet another solution to the calorie-testing problem is as follows:

Integer method definition • instance 
analyzeCalories 
  self > 1600 
    ifTrue: [Transcript show: 'You have had enough'; cr] 
    ifFalse: [self < 1200 
               ifTrue: [Transcript show: 'You need more'; cr] 
               ifFalse: [Transcript show: 'You have eaten wisely'; cr]] 
Workspace
1700 analyzeCalories. 
1400 analyzeCalories. 
1100 analyzeCalories 
Transcript 
You have had enough 
You have eaten wisely 
You need more 

Note that the ifTrue:ifFalse: expression's second argument is an ifTrue:ifFalse: expression. This embedded ifTrue:ifFalse: expression is evaluated only if the number of calories is 1600 or less.