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

temperature
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}"
  1. temperature ← 72

    1temperature→ 72 = 72  #@temperature=55, 90
  2. status ← comfortable

    4  status = "warm"5else6  status→ comfortable = "comfortable"7end
  3. puts "temperature=#{temperature}"

    9puts "temperature=#{temperature72}"10puts "status=#{statuscomfortable}"
    outputtemperature=72
    status=comfortable
  1. temperature ← 55

    1temperature→ 55 = 55
  2. status ← comfortable

    4  status = "warm"5else6  status→ comfortable = "comfortable"7end
  3. puts "temperature=#{temperature}"

    9puts "temperature=#{temperature55}"10puts "status=#{statuscomfortable}"
    outputtemperature=55
    status=comfortable
  1. temperature ← 90

    1temperature→ 90 = 90
  2. status ← warm

    3if temperature90 >= 804  status→ warm = "warm"5else
  3. puts "temperature=#{temperature}"

    9puts "temperature=#{temperature90}"10puts "status=#{statuswarm}"
    outputtemperature=90
    status=warm

Follow the Branch

  1. temperature starts at 72.
  2. Ruby checks whether temperature >= 80.
  3. 72 is below 80, so the else branch runs.
  4. status becomes comfortable.
  5. The program prints temperature=72 and status=comfortable. | temperature | check | status | | --- | --- | --- | | 55 | 55 >= 80 is false | comfortable | | 72 | 72 >= 80 is false | comfortable | | 90 | 90 >= 80 is true | warm |

Exercise: conditionals.rb

Reproduce status=comfortable for temperature 72, then try 55 and 90 and predict the branch result.