Miscellaneous Ruby Commands

Ruby break Statement:

Syntax:

break

Terminates the most internal loop. Terminates a method with an associated block if called within the block (with the method returning nil).

Example:

#!/usr/bin/ruby

for i in 0..5
   if i > 2 then
      break
   end
   puts "Value of local variable is #{i}"
end

This will produce the following result:

Value of local variable is 0
Value of local variable is 1
Value of local variable is 2

Ruby next Statement:

Syntax:

next

Jumps to next iteration of the most internal loop. Terminates execution of a block if called within a block (with yield or call returning nil).

Example:

#!/usr/bin/ruby

for i in 0..5
   if i < 2 then
      next
   end
   puts "Value of local variable is #{i}"
end

This will produce the following result:

Value of local variable is 2
Value of local variable is 3
Value of local variable is 4
Value of local variable is 5

Ruby redo Statement:

Syntax:

redo

Restarts this iteration of the most internal loop, without checking loop condition. Restartsyield or call if called within a block.

Example:

#!/usr/bin/ruby

for i in 0..5
   if i < 2 then
      puts "Value of local variable is #{i}"
      redo
   end
end

This will produce the following result and will go in an infinite loop:

Value of local variable is 0
Value of local variable is 0
............................
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s