Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
if-else

How to write an if-else condition in Ruby

Educative Answers Team

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

RELATED TAGS

ruby
if-else
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring