IF ELSE in Ruby Language
When it comes to programming, decision-making is a fundamental concept. In the Ruby programming language, as in
many other programming languages, you can make decisions using conditional statements. One of the most commonly used conditional statements in Ruby is the “IF-ELSE” statement. In this post, we’ll explore how to use IF-ELSE statements in Ruby with examples.IF Statement in Ruby:
The IF
statement is used to execute a block of code only if a certain condition is true. Here’s the basic syntax:
if condition
# Code to execute if condition is true
end
For example, let’s say you want to print a message if a variable x
is greater than 10:
x = 12
if x > 10
puts "x is greater than 10"
end
In this example, “x is greater than 10” will be printed to the console because the condition x > 10
is true.
ELSE Statement in Ruby:
The ELSE
statement is used in conjunction with IF
to execute a block of code when the condition is false. Here’s the syntax:
if condition
# Code to execute if condition is true
else
# Code to execute if condition is false
end
Let’s modify our previous example to include an ELSE
statement:
x = 8
if x > 10
puts "x is greater than 10"
else
puts "x is not greater than 10"
end
In this case, “x is not greater than 10” will be printed because the condition x > 10
is false.
ELSIF Statement in Ruby:
You can also handle multiple conditions using the ELSIF
statement. It allows you to check multiple conditions in sequence. Here’s the syntax:
if condition1
# Code to execute if condition1 is true
elsif condition2
# Code to execute if condition2 is true
else
# Code to execute if none of the conditions are true
end
Let’s say you want to check if a number is positive, negative, or zero:
num = -5
if num > 0
puts "Number is positive"
elsif num < 0
puts "Number is negative"
else
puts "Number is zero"
end
In this example, “Number is negative” will be printed because num < 0
is true.
Combining Conditions:
You can also combine conditions using logical operators such as &&
(AND) and ||
(OR). For instance:
age = 25
income = 50000
if age > 21 && income > 30000
puts "You qualify for the loan."
else
puts "You do not qualify for the loan."
end
In this example, “You qualify for the loan” will be printed only if both conditions are true.
Discover more from PiEmbSysTech
Subscribe to get the latest posts sent to your email.