Choose a path with conditions
Use if, elsif, and else to make decisions.
- 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.
1temperature = 18
2if temperature < 10
3 puts "cold"
4elsif temperature < 20
5 puts "mild"
6else
7 puts "warm"
8endmild
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.
Label a temperature
Read an integer. Print cold below 15, mild from 15 through 24, and warm at 25 or above.
- Cold day
- Mild day
- Warm day
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…