while true x loop

Asked

Viewed 444 times

0

Developing some scripts in Ruby I come across the following situation:

There are indeed several Repetition Structures, but 2 in particular caught my attention. while true and loop do. Both generate what everyone knows as "infinite looping". But there is something that makes one more performative than the other!?

In the case of loop do it will perform the action infinitely or until I establish (establish) a stopping condition. Ex:

count = 1
loop do 
  puts count
  count += 1
end

But taking this logic to the while true we have implicitly the explanatory "he will perform as long as the condition is true", but what condition!? Ex:

count = 1
while true 
  puts count
  count += 1
end

In addition to the syntax issue, there is something that differentiates them in the sense of performance or there may be something in my code that could cause problems in one of the 2 loops (maybe this 'true' no while)?

When should I use each of them?

2 answers

1

Good evening, I do not use ruby but I believe that there are no performance differences between loops of repetition, of course that varies from language to language. The While (true) will perform endlessly already loop do I believe it’s a Do While() ie it will perform at least once the loop before checking the stop condition.

As for the loop I believe that your application will lock if it has interface obviously, because the thread that contains the infinite loop will consume all processing. If your program is console has no problems however it should be intersex put some kind of sleep so it doesn’t consume too much of your CPU.

Micro controllers work with loop While(true) for example using 100% of the processing.

1


Ruby is a language that allows different ways to the same end. The intention is to increase the semantics of the code, making it more readable. In the case cited, it is an infinite loop.

The difference between constructions while and loop in Ruby is that the while accept a condition. This condition is put right after the keyword. See:

while tem_internet? # <<< condição é tem_internet?
  navegar '/'
end

So tem_internet? for evaluate for false, the loop will stop. The equivalent of the above code with a construction loop would be:

loop do
  break unless tem_internet?
  navegar '/'
end

In the case of while true, the condition is always true and so it is infinite.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.