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?
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.
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.
You can run a for loop infinitely by writing it without any exit condition.
loop do
puts 'foo'
puts 'bar'
sleep 300
end
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With