Joe Half Face
Joe Half Face

Reputation: 2333

Infinite 'while' loop

Basically it is Rails code, but here is pure Ruby problem. For you to know - @test.source is some String, which can contain ' ' (spaces). The aim is to delete all unnecessary spaces, which go after first. For example,%some word' '' ' should leave %some word' ', %another word' '' '' ' should leave %another word' ' and so on.

for i in [email protected]
      if @test.source[i] == ' '
          i=i+1
          while @test.source[i] == ' '
              @test.source[0...i].chop
          end
      else
          i+=1
      end
  end

For some reason this loop (obviosly 'while') is infinite. Why?

Upvotes: 1

Views: 277

Answers (1)

Dai
Dai

Reputation: 155708

You aren't incrementing i within the while loop, so the while loop will always compare the specified character with ' ' without ever moving on.

Change it to this:

      <% while @test.source[i] == ' ' %>
          <% @test.source[0...i].chop %>
          <% i=i+1 %>
      <% end %>

...but even then, there are still problems with your code. It's an exercise for the reader to see the remaining issues. :)

Upvotes: 1

Related Questions