Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 903
Andrew Walz Avatar asked Nov 26 '14 01:11

Andrew Walz


People also ask

What is infinite loop give example?

What is an Infinite Loop? An infinite loop occurs when a condition always evaluates to true. Usually, this is an error. For example, you might have a loop that decrements until it reaches 0.

Is it possible to create a loop that never ends?

An infinite loop is a sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over.

Can we create infinite loop using for loop?

You can run a for loop infinitely by writing it without any exit condition.


3 Answers

loop do
  puts 'foo'  
  puts 'bar'  
  sleep 300
end
like image 171
Todd A. Jacobs Avatar answered Oct 19 '22 16:10

Todd A. Jacobs


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
like image 44
vgoff Avatar answered Oct 19 '22 17:10

vgoff


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
like image 1
Abdelrahman Farag Avatar answered Oct 19 '22 16:10

Abdelrahman Farag