In Ruby, if-else
statements are used to perform conditional operations. The basic syntax for an if-else statement is straightforward and quite similar to other programming languages. Below is an explanation of how to use if-else in Ruby with examples.
Syntax
if condition
# code to execute if condition is true
elsif another_condition
# code to execute if another_condition is true
else
# code to execute if all previous conditions are false
end
Example if-else
age = 18
if age < 18
puts "You are a minor."
elsif age == 18
puts "You just became an adult."
else
puts "You are an adult."
end
Explanation
- If
age
is less than 18, it prints "You are a minor."
- If
age
equals 18, it prints "You just became an adult."
- Otherwise, it prints "You are an adult."