Ruby - Using catch and throw

Introduction

Ruby catch and throw can break out of a block of code when some condition is met.

It is like the goto statement in some other programming languages.

The block must begin with catch followed by a symbol, a unique identifier preceded by a colon, such as :done or :finished.

The block itself may be delimited either by curly brackets or by the keywords do and end, like this:

# think of this as a block called :done 
catch( :done ){ 
   # some code here 
}  

# and this is a block called :finished 
catch( :finished ) do 
   # some code here 
end 

Inside the block, you can call throw with a symbol as an argument.

Normally you would call throw when some specific condition is met.

Demo

catch( :finished) do    
   print( 'Enter a number: ' ) 
   num = gets().chomp.to_i #   w w  w. jav a  2 s.  c o m
   if num == 0 then  
      throw :finished # if num is 0, jump out of the block 
   end          
end 

puts( "Finished" )

Result

You can, in fact, have a call to throw outside the block, like this:

def dothings( aNum ) 
   i = 0 
   while true 
      puts( "I'm doing things..." ) 
      i += 1 
      throw( :done ) if (i == aNum )  
   end 
end 
catch( :done ){   # this is the :go_to_tea block 
      dothings(5)    
} 

You can have catch blocks nested inside other catch blocks, like this:

Demo

def dothings( aNum ) 
   i = 0 # w  w  w . j a  va 2  s. c om
   while true 
      puts( "I'm doing things..." ) 
      i += 1 
      throw( :done ) if (i == aNum )  
   end 
end 

catch( :finished) do    
   print( 'Enter a number: ' ) 
   num = gets().chomp.to_i 
   if num == 0 then throw :finished end          
      puts( 100 / num )    
   catch( :done ){ 
      dothings(5)    
   } 
   puts( "Things have all been done. Time for tea!" ) 
end

Result