How to Use the if…else Statement in Ruby



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:

if condition
  # code to execute if the condition is true
  # code to execute if the condition is false

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"
  puts "#{num} is odd"

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"
  puts "#{num} is zero"

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.