Ruby if-else statements are fundamental control structures used for decision-making in Ruby programming. They allow you to execute different code blocks based on specified conditions.
The basic syntax of an if-else statement in Ruby is as follows:
if condition
# code to execute if condition is true
else
# code to execute if condition is false
end
If-else statements evaluate a condition and execute the corresponding code block. Here's a simple example:
age = 18
if age >= 18
puts "You are eligible to vote."
else
puts "You are not eligible to vote yet."
end
In this example, the program checks if the age
is 18 or older. If true, it prints the eligibility message; otherwise, it prints the ineligibility message.
For more complex decision-making, you can use elsif
to check multiple conditions:
score = 85
if score >= 90
puts "A"
elsif score >= 80
puts "B"
elsif score >= 70
puts "C"
else
puts "D"
end
This code assigns a letter grade based on the numerical score. It checks conditions in order and executes the first matching block.
Ruby also supports inline if statements for concise, single-line conditionals:
puts "It's cold!" if temperature < 10
This line prints "It's cold!" only if the temperature is less than 10.
elsif
for multiple related conditionsTo further enhance your understanding of conditional logic in Ruby, explore these related topics:
Mastering if-else statements is crucial for writing efficient and logical Ruby code. Practice with various conditions to become proficient in using these control structures effectively.