Loading
0x30Lesson 4 of 6

Choose a path with conditions

Use if, elsif, and else to make decisions.

13 min 4-question quiz 1 code exercise
By the end of this lesson you can
  • Branch on a condition and print the matching result.

An if expression runs a block when its condition is true. Add elsif for another condition and else for the remaining path. Ruby uses end to close the conditional. Only false and nil are falsey; values such as 0 and empty strings are truthy.

main.rb
1temperature = 18
2if temperature < 10
3  puts "cold"
4elsif temperature < 20
5  puts "mild"
6else
7  puts "warm"
8end
Output
mild

Comparison operators include ==, !=, <, <=, >, and >=. Use && for logical “and” and || for logical “or”. Indentation is conventional and improves readability, while end marks where the block finishes.

Key takeaways

  • Branch on a condition and print the matching result.

  • Ruby methods and blocks help express operations clearly.

  • Read each result and error message as feedback about your code.

Lesson quiz

4 questions · pass with 3 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Ruby

Write Ruby in the editor and run it against sample input. Your code is sent to Wandbox to run.

Exercise 1

Label a temperature

+25 XP

Read an integer. Print cold below 15, mild from 15 through 24, and warm at 25 or above.

  • Cold day
  • Mild day
  • Warm day
main.rb
Loading editor…

Ruby runs through Wandbox, a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Did you like the lesson? 😆👍
Consider a donation to support our work: