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




RUBY - BREAK & NEXT


Break Statement:


We are going to see the use of break statement to get out of a loop.


So, we go into the loop first. Then we specify the condition part in an if statement.


And place a break inside the if statement.


Example :



i=1
loop do   
	puts i;
	i = i+1; 
	 
	if i > 10   
    	break   
  	end   
end 


  1. First we initialize the value of i with 1.

  2. Next we write the loop do statement, so that we go into the loop.

    loop do

  3. Next we print the value of i.

    puts i;

  4. And increment the value of i by 1.

    i = i+1;

  5. Then when it finds the if statement with the condition i > 10,

    if i > 10
    	break
    end


    It doesn't immediately gets into the if block as the condition i > 10 is not yet true. So, it continues to be in the loop until the condition is met.

    And when the condition is met, it gets into the if block and comes out of the loop, since the break statement is present.

So, it is the break statement that is causing the control to come out of the loop.


Next Statement:


next is used inside a loop to skip that particular iteration.


Example :



for i in 1..10 do 
	if i > 5
    	next
    end 
  	puts i 
end 



So, in the above programme, only the values from 1 to 5 will be printed. As in the if block we have specified the next statement,


if i > 5
	next
end

So, whenever the value of i is more than 5. The next statement is executed inside the if block. Which is causing to skip the current iteration.