Introduction
These are the most often-used concepts and I am going to discuss all of them in detail. Unlike other programming languages, ruby has too many iterators and loops. Their syntax of them is also a bit weird. But I simply summarized all of them.
Loops
In programming sometimes we need to repeat an action/task/instruction/function a particular number of times. This can be done in 2 ways using iterators and loops. Ruby provides an iteration option also to do the same task.
Even though they are doing the same task there is a difference. loops execute until the given condition is true or false.
there are 3 types of loops in ruby
while
for
until
While
It continues execution until the given condition is false. We have to care about it while working. skipping any part leads to an infinite loop.
Steps we have to keep in mind
Initialization
condition
increment/decrement
let's try to write a simple code using a while loop.
i = 0 #initilization
while (i < 5) #condition
puts i
i +=1 #increment
end
DON'T forget to close the loop with the "end " keyword.
For
The working of this is also same as while. But it can only allow doing iterations when you know how many times the loop gonna execute.
Syntax: for variable in range(expression)
It seems like python for loop syntax. But there is a difference in defining a range. In that place, we define the range in two ways.
starting_value..ending_value (It includes the ending_value)
starting_value...ending_value (it excludes the ending_value)
the dots in between the starting and ending values do not exceed more than 3. Because I tried to place 4 dots to exclude the last 2 values. Hahaha
DO try to code this
for i in 1..5 do #include the last value
print i
end
output:
12345
Until
This is quite similar to the while loop. The syntax is also the same. But it continues execution until the given condition is true which is just the opposite of the while loop.
The initialization, condition, and increment/decrement are also selfsame. Let's directly code this for better understanding.
i = 5 #initilization
until i == 1 #true condition
print i
i -= 1 #increment
end
output:
5432
Iterators
Before this concept, I thought that another name for a loop is an iterator. Yes, we indeed call for, while, and until loops as iterators. Iterators are methods that are supported by collection. The collection may be a range, array, or hashes. Ruby gives some more flexibility with iterators like
The thing about all these iterator methods is their functionality can be understand by the method name itself
each
collect
times
upto
downto
step
each_line
Just DO try to know their usage and syntax quickly
Note: All the iterators are finite means they can only implement if and only if have to know how many times the loop gonna execute.
each
It returns all the elements in the collection.
As we stated above all the iterators are methods we can call by using "." operators. Things get more clarity when we see.
The syntax is: (collection).each do |variable|
The variable name between | | can be anything you like. It's just a placeholder for each element. The syntax for the above-mentioned is almost the same with a little bit of difference.
(0..9).each do |i| #here the collection is range
puts i
end
output:
0123456789
collect
Runs on all the elements in the collection. Returns the entire array or hash. This will work out in range or array or hash. But we find this method most used in the arrays and hashes.
syntax: collection.collect { |variable| (operation) }
a = [1, 2, 3]
b = a.collect{ |i| i*2}
puts b
output:
2
4
6
Times
This is my favorite iterator. No complex syntax, times itself indicating that we just directly define how many times we gonna iterate.
syntax: integer.times do |varible_name|
5.times do i #start with 0
print i
end
output:
01234
upto & downto
The syntax and working of both methods are the same but in reverse order. In this, we have to define both top and bottom values.
upto syntax: top.upto( bottom) do |variable|
downto syntax: top.downto( bottom) do |variable|
In the upto method, the bottom is always greater than the top.
In downto method, the top is always greater than the bottom.
1.upto(5) do |i| #it includes both top and bottom values
print i
end
output:
12345
5.downto(1) do |i|
print i
end
output:
54321
Step
The name itself indicates that it iterates the entire array by stepping specifically in a given range. This method takes one value as an argument it should be a positive integer only.
syntax: collection.step(stepping_value) do |variable|
(1..10).step(3) do |i|
puts i
end
output:
1
4
7
10
In the above example, it is only printing a few numbers by skipping the numbers in the given range
(1 , 2, 3, 4 , 5, 6, 7 , 8, 9, 10)
Next
This can be used in conditional statements and iterations. The main function of this keyword is it just skips that particular iteration.
for i in (1..5)
puts i
if i % 2 == 0 #if a number divisible by 2 then we want to skip that iteration.
next
end
end
output:
1
3
5
Break
It is pretty self-explanatory. after reaching the particular condition it just comes out from the loop no matter how big the iteration is. Like "next" it is also used in conditional statements and iterations.
Try to implement the above code using a break statement.
for i in (1..5)
puts i
if i % 2 == 0
break
end
end
output:
1
2
The above code tells that in the range from 1-5 numbers if I found any even number I have to come out of the loop. It starts with the number "1" it just prints the "1" in the console and checks the condition. After this, it reaches "2" as we print the number first before checking the condition. It just prints the number in the console and checks the condition. For number "2" the condition is true so the if block executes. In that block, we use a "break" statement it comes out from the entire loop.
Conclusion
This is all about the loop and control statements in the ruby. Hope you learn something. I will be with some arrays and hashes in the next blog. Stay tuned and happy learning.