Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




RUBY - FOR LOOP


Fot Loop is another kind loop used by Ruby. Let us see it in the below example to print the numbers from 1 to 10.


Example of 'for' loop:


Example :



for i in 1..10 do   
  puts i   
end 



Now, if we break the contents of for loop, we get :

  1. Initialisation part : It is run before the loop starts.

    for i in 1..10


    i is getting initialized with value 1. So, the value 1 before the two dots (i.e. 1..10) is getting initialized to i.

  2. Conditional part : It states the condition for running the loop.

    for i in 1..10


    It says, continue to be in the loop until the value of i is not more than 10. So, the value 10 after the two dots (i.e. 1..10) is considered as the conditional statement.

  3. Increment part : It is run each time after the loop.

    You do not have to worry, as it happens internally in Ruby for loop. i.e. Every time the value gets incremented by 1.

All together forms the for loop.


for i in 1..10 do
	puts i
end

So, for loop is quite better compared to while loop. As the lines of codes gets reduced.


Example of 'for' 'each' loop:


We will be learning about it in the Arrays section of Ruby.