Ruby | Control Flow Alteration

Prerequisite : Decision Making , Loops

Ruby programming language provides some statements in addition to loops, conditionals, and iterators, which are used to change the flow of control in a program.
In other words, these statements are a piece of code that executes one after another until the condition is true and when the condition becomes false then code terminated. The following are the statements which can alter the control flow in a Ruby program:

  1. break statement
  2. next statement
  3. redo statement
  4. retry statement
  5. return statement
  6. throw/catch statement

    break Statement

    In Ruby, Break statement is used to exit a loop when the condition is true. Break statement is basically used in while loop because in while loop the output is printed till the condition is true, when the condition is false the loop exited. The break statement is used inside the loop. The break statement are executed by break keyword. Break statement can also be used in for, while, and case control statements.



    Syntax:

    break

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to illustrate break statement
       
    #!/usr/bin/ruby  
      
    i = 1
      
    # using while loop
    while true   
      
        if i * 6 >= 30
              
            # using break statement
            break  
              
        # ending of if statement    
        end   
          
        puts i * 6   
        i += 1
          
    # ending of while loop
    end  

    chevron_right

    
    

    Output:

    6
    12
    18
    24
    

    Explanation: In above example, break statement is used to stop the execution of while loop when the condition if i * 6 >= 30 becomes true. Otherwise loop goes to infinite.

    next Statement

    In Ruby, next statement is used to jump to the next iterator of given loop. The next statement is identical to continue statement in C and Java language. When the next statement is used no other iteration will be performed. Generally, the next statement is used in for and while loop.

    Syntax:

    next

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to illustrate next statement
       
    #!/usr/bin/ruby  
      
    # using for loop
    for t in 0...10 
      
       # using if statement  
       if t == 5 then 
      
         # using next statement  
          next
      
      # ending of if   
       end   
      
       # displaying values
       puts t 
      
    # end of for loop  
    end  

    chevron_right

    
    

    Output:

    0
    1
    2
    3
    4
    6
    7
    8
    9
    

    Explanation: In the above program, 5 will not be printed in the output due to next statement. So here at 5 next statement will cause to skip it and continue from next statement in program.

    redo Statement

    The redo statement is used to restart the current iteration of a loop or the iterator. There is a difference between the redo and next statement. next statement always transfers the control to the end of the loop where the statement after the loop can start to execute, but redo statement transfer the control back to the top of block or loop so that iteration can start over.


    Syntax:

    redo

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to demonstrate the redo statement
      
    # defining a variable
    val = 0
      
    # using while loop which should give
    # output as 0,1,2,3 but here it will 
    # output as 0,1,2,3,4
    while(val < 4
      
    # Control returns here when 
    # redo will execute
    puts val
    val += 1
      
    # using redo statement
    redo if val == 4
      
    # ending of while loop
    end

    chevron_right

    
    

    Output:

    0
    1
    2
    3
    4
    

    Explanation: In the above program, redo statement will transfer the control to puts val which is the first expression of while loop. It is neither going to retest the loop condition nor going to fetch the next element from the iterator. So, here while loop will print 0,1,2,3,4 instead of 0,1,2,3.

    retry Statement(deprecated in recent versions)

    retry statement is used to restart an iterator based on a certain condition or any method invocation from the starting. In simple words, retry statement transfers the control at the beginning. Generally, a retry statement is used rarely. It will only work till Ruby version 1.8.

    Note: retry statement has been removed from the Ruby version 1.9 onwards because it is considered deprecated language feature. So it will hardly run on online IDE’s because mostly using version above 1.8.

    Syntax:

    retry

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to demonstrate the retry statement
      
    # variable
    var = 7
      
    # Iterate 7 times from 0 to 7-1
    var.times do |val| 
      
    # display iteration number
    puts val 
      
    # If we've reached 6
    if val == 6
      
    # Decrement val and user won't
    # reach 6  next time
    var = var - 1 
      
    # Restart the iteration
    # using retry statement
    retry 
      
    # end of if 
    end
      
    # end of do..end
    end

    chevron_right

    
    

    Output:

    0
    1
    2
    3
    4
    5
    6
    0
    1
    2
    3
    4
    5
    

    Explanation: In above program, when the control goes to retry statement then it transfers that control to var.times do |val| . Now here the value of var variable is updated i.e. 5. So user won’t reach 6 to next time and retry statement will not execute again.


    return statement

    This is used to exit from a method, with or without a value. It always returns a value to its caller. There are many options with the return statement. If there is no expression used with return statement then it always returns the value of method as nil. A list of expression after the return statement is always separated by the comma(,) In this case, the value of the method will be an array containing the values of those specified expressions.

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to demonstrate the return statement 
      
    #!/usr/bin/ruby
      
    # defining a method 'geeks'
    def geeks
          
       # variables of method
       val1 = 61
       val2 = 55
      
    # returning multiple values   
    return val1, val2
      
    # this statement will not execute
    puts "Hello Geeks"
      
    # end of the method
    end
      
    # variable outside the method to 
    # store the return value of the method
    value = geeks
      
    # displaying the returned values
    puts value

    chevron_right

    
    

    Output:

    55
    61
    

    Explanation: In above example, method geeks has a return statement which return the two values i.e. val1 and val2 to its caller. Here value is the variable which stored the returned values. The important point is that the statement puts “Hello Geeks” after return statement doesn’t execute because statements after the return statement will not execute inside a method.

    throw/catch Statement

    throw and catch are used to define a control structure which can be considered as a multilevel break. throw is used to break the current loop and transfer the control outside of the catch block. The best thing about throw is that it can break out of the current loop or methods or we can say it can cross any number of levels. Here, catch defines a “labeled block” of code which causes to exit by the throw block. More details will be discussed In Ruby Exception Handling section.

    Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Ruby program to illustrate the throw/catch statement
    # for altering the control flow
      
    # defining a method
    def lessNumber(num)
          
        # using throw statement
        # here 'numberError' is its label
        throw :numberError if num < 10
          
        # displaying result 
        puts "Number is Greater than 10!"
    end
      
      
    # catch block
    catch :numberError do
          
        # calling method
        lessNumber(11)
        lessNumber(78
          
        # exits catch block here
        lessNumber(7)
        lessNumber(4)
    end
      
    puts "Outside Catch Block"

    chevron_right

    
    

    Output:

    Number is Greater than 10!
    Number is Greater than 10!
    Outside Catch Block
    

    Explanation: In above program, 11 is passed to method lessNumber to check whether it is greater than 10 or not. 11 is greater than 10 so statement will print out on display and next statement of catch block will execute. Now 78 is passed to the method call, which is checked and it is greater than 10 so statement will print out on screen. But as soon as 7 is passed which is less than 10 throw: numberError cause the catch block to exits and all the statements skip out and last statement “Outside Catch Block” will print. So here as soon as the condition becomes false throw causes the catch block to exit the catch block from execution.



    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



    Improved By : nidhi_biet



    Article Tags :

    1


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.