Andrew Walz
Andrew Walz

Reputation: 750

Creating an infinite loop

I'm trying to create an infinite loop, where a block of code will be executed forever.

All loop documentation I have found warns against creating an infinite loop, but no examples of a working one.

If I have a block of code:

{ puts "foo"  
  puts "bar"  
  sleep 300 }

How would I go about running this block forever?

Upvotes: 25

Views: 28519

Answers (4)

vgoff
vgoff

Reputation: 11313

Here are some examples of infinite loops using blocks.

Loop

loop do
  puts "foo"  
  puts "bar"  
  sleep 300
end

While

while true
  puts "foo"  
  puts "bar"  
  sleep 300
end

Until

until false
  puts "foo"  
  puts "bar"  
  sleep 300
end

Lambda

-> { puts "foo" ; puts "bar" ; sleep 300}.call until false

There are a few variations of the lambda as well, using the non-stabby lambda syntax. Also we could use a Proc.

Begin..End

begin
  puts "foo"  
  puts "bar"
  sleep 300
end while true

Upvotes: 24

Abdelrahman Farag
Abdelrahman Farag

Reputation: 399

I have tried all but with inputs loop only worked as infinty loop till I get a valid input:

loop do
    a = gets.to_i
    if (a >= 2)
        break
    else 
        puts "Invalid Input, Please enter a correct Value >=2: "
    end
end

Upvotes: 2

Rahul Dess
Rahul Dess

Reputation: 2587

1) While loop:

While 1==1 # As the condition 1 is equal to 1 is true, it always runs.
    puts "foo"  
    puts "bar"  
    sleep 300
   end

2) Recursion :

    def infiniteLoop # Using recursion concept
      puts "foo"
      puts "bar"
      sleep 300
      infiniteLoop #Calling this method again    
    end

EDIT : I thought this would work, but as Gabriel mentioned, we would get SystemStackError.

3) Loop

   loop do
    puts "foo"
    ....
   end

4) Using unless

unless 1 == 2  # Unless 1 is equal to 2 , it keeps running
 puts "foo"
 ...
end

Upvotes: -6

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84333

loop do
  puts 'foo'  
  puts 'bar'  
  sleep 300
end

Upvotes: 47

Related Questions