Conditional statements and loops

Conditional statements and loops allow developers to branch off from the serial flow of execution of code and also iterate through the code. Ruby provides multiple ways to do this job. Let's look at a few of them.

The if statement

The if statement is pretty much a basic branching statement that's provided by many programming languages. It's pretty much how we use the "if" statement in natural language—if it's true, do this; if it's not, do something else.

x=2
if x == 2
  puts "True"
else
  puts "False"
end

If we need to check for multiple conditions, we get an elsif statement, that we can embed between the if and else statements:

height = 164 if height > 170 puts "Tall" elsif height > 160 puts "Normal" else puts "Dwarf" ...

Get Mastering Chef now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.