How to write an if-else condition in Ruby

if-else is a conditional statement that runs a set of instructions depending on whether the condition is true or false.

svg viewer

Syntax

svg viewer

Code

In the code below, if a number is less than ten the line “Try increasing your guess number” is printed; if it’s greater than ten, the line (“Try decreasing your guess number”) is printed.

# number variable.
number = 10
# if-else statements
if number < 10
puts "Try increasing your guess number"
elsif number == 10
puts "You got this one!"
else
puts "Try decreasing your guess number"
end

The figure below illustrates how the code above works:

svg viewer

Code

Here’s another example:

# number variable.
X = 12
# if-else statements
if X > 10 && X < 15
puts "The number X must be greater than 10 and less than 15"
else
puts "The number X doesn't fall in the range"
end
Copyright ©2024 Educative, Inc. All rights reserved