Foundations
Conditionals
Use if and else to choose work based on a condition.
conditional
An `if` expression runs one branch when its condition is true and another branch when it is false.
Conditionals
conditionals.rb
Replay: real traced execution (multi-file project)
temperature = 72
if temperature >= 80
status = "warm"
else
status = "comfortable"
end
puts "temperature=#{temperature}"
puts "status=#{status}"
temperature = 55
if temperature >= 80
status = "warm"
else
status = "comfortable"
end
puts "temperature=#{temperature}"
puts "status=#{status}"
temperature = 90
if temperature >= 80
status = "warm"
else
status = "comfortable"
end
puts "temperature=#{temperature}"
puts "status=#{status}"
temperature ← 72
1temperature→ 72 = 72 #@temperature=55, 90status ← comfortable
4 status = "warm"5else6 status→ comfortable = "comfortable"7endputs "temperature=#{temperature}"
9puts "temperature=#{temperature72}"10puts "status=#{statuscomfortable}"outputtemperature=72 status=comfortable
temperature ← 55
1temperature→ 55 = 55status ← comfortable
4 status = "warm"5else6 status→ comfortable = "comfortable"7endputs "temperature=#{temperature}"
9puts "temperature=#{temperature55}"10puts "status=#{statuscomfortable}"outputtemperature=55 status=comfortable
temperature ← 90
1temperature→ 90 = 90status ← warm
3if temperature90 >= 804 status→ warm = "warm"5elseputs "temperature=#{temperature}"
9puts "temperature=#{temperature90}"10puts "status=#{statuswarm}"outputtemperature=90 status=warm
Follow the Branch
temperaturestarts at72.- Ruby checks whether
temperature >= 80. 72is below80, so theelsebranch runs.statusbecomescomfortable.- The program prints
temperature=72andstatus=comfortable. | temperature | check | status | | --- | --- | --- | | 55 |55 >= 80is false | comfortable | | 72 |72 >= 80is false | comfortable | | 90 |90 >= 80is true | warm |
Exercise: conditionals.rb
Reproduce status=comfortable for temperature 72, then try 55 and 90 and predict the branch result.