How to Use the if…else Statement in Ruby

09/18/2021

Contents

In this article, you will learn how to use the if…else statement in Ruby.

The if…else Statement

The if…else statement is a control flow structure in Ruby that allows you to execute different code blocks based on a condition. Here’s the basic syntax for using the if…else statement in Ruby:

Syntax
if condition
  # code to execute if the condition is true
else
  # code to execute if the condition is false
end
Example

Here’s an example that uses the if…else statement to determine if a number is even or odd:

num = 4

if num % 2 == 0
  puts "#{num} is even"
else
  puts "#{num} is odd"
end

In this example, the code inside the if block will execute if the condition num % 2 == 0 is true, which means that the number is even. If the condition is false, the code inside the else block will execute, which means that the number is odd.

You can also use the if…else statement to chain multiple conditions together using elsif:

num = 10

if num < 0
  puts "#{num} is negative"
elsif num > 0
  puts "#{num} is positive"
else
  puts "#{num} is zero"
end

In this example, the first condition checks if the number is negative, the second condition checks if it’s positive, and the final else block is executed if neither of the conditions is true.

It’s important to note that the if…else statement requires a boolean value as its condition. If the condition is not a boolean value, Ruby will attempt to convert it to one using the to_bool method.