Book Image

Mastering Chef

By : Mayank Joshi
Book Image

Mastering Chef

By: Mayank Joshi

Overview of this book

Table of Contents (20 chapters)
Mastering Chef
About the Author
About the Reviewers
Knife and Its Associated Plugins
Data Bags and Templates

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.

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

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"
  puts "Dwarf"

The fun part of doing this in Ruby is that you can assign values returned by the if, elsif, and else blocks. For example, you might want to save the Tall, Normal, or Dwarf message inside some variable for later use. You can do this...