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
............................

Giving a timeout in ruby

sleep(num_secs)

The ‘num_secs’ value can be an integer or float. Also, if you’re writing this within a Rails app, or are using ActiveSupport library elsewhere in your project, you can construct longer intervals using the following convenience syntax:

sleep(4.minutes)
# or, even longer...
sleep(2.hours); sleep(3.days) # etc., etc.
#Or shorter
sleep(0.5) #Half a second