Conditional statements and loops allow developers to branch off from the serial flow of execution of code and also iterate through the code. Ruby provides multiple ways to do this job. Let's look at a few of them.
The if statement
The if statement is pretty much a basic branching statement that's provided by many programming languages. It's pretty much how we use the "if" statement in natural language—if it's true, do this; if it's not, do something else.
x=2
if x == 2
puts "True"
else
puts "False"
end
If we need to check for multiple conditions, we get an elsif statement, that we can embed between the if and else statements:
height = 164
if height > 170
puts "Tall"
elsif height > 160
puts "Normal"
else
puts "Dwarf"
end
The fun part of doing this in Ruby is that you can assign values returned by the if, elsif, and else blocks. For example, you might want to save the Tall, Normal, or Dwarf message inside some variable for later use. You can do this quickly in Ruby as follows:
size = if height > 170
"Tall"
elsif height > 160
"Normal"
else
"Dwarf"
end
Depending on the value of height, whichever block is executed, it'll eventually become the value of size.
The unless statement
Often, you would want to make a choice, where if a condition is not true, do this or else do that. In most of the programming languages, and Ruby too, you can accomplish this using the negation operator (!) before the condition along with the if statement. However, Ruby provides a more convenient and natural way to handle this through the unless statement. You can just say this: unless condition, do this or else do that.
Many a times, we'll have multiple conditions to deal with and, if that's the case, then though if then else can be used, it will become messy eventually. The case/when statement is a much better option in this case:
day_today = "Sunday"
case
when day_today == "Sunday"
puts "Holiday!"
when day_today == "Monday"
puts "Start of week !"
when day_today == "Wednesday"
puts "Mid week crisis !"
end
Alternatively, an even better and concise way to express this would be as follows:
day_today = "Sunday"
case day_today
when "Sunday"
puts "Holiday!"
when "Monday"
puts "Start of week!"
when "Wednesday"
puts "Mid week crisis!"
end
The while loop
A while loop can continue to execute statements until the condition stated is false. In other words, a while loop can continue to execute statements "while the condition is true".
count = 1
while count < 10
puts count
count += 1
end
This will print the numbers 1 to 9.
The until loop
As unless is the opposite of if, until is the opposite of while. It will continue to iterate over the block of code until the given condition is true:
count = 10
until count == 0
puts count
count -= 1
end
The for loop
The for loop in Ruby is more like a foreach loop in languages such as Perl or PHP. It's mostly used for iterating over an array or a hash:
x = [1,2,3,4,5]
for item in x
puts x
end
This will print all elements of the x array, one at a time.