How do I use the break command within two loops in Ruby?

Asked

Viewed 299 times

4

When the "break" command is executed in "if" there is a way to exit the internal and external loop ? not just one ?

while (i < maior) do
  if tam1>tam2
     for i2 in 0 .. tam2 do
        if(palavra1[i]==palavra2[i2])
           iguais = palavra1[i2]
           posicao = i
           break #Quero que saia desse laço e do outro
        end
     end
  else
      for i2 in 0 .. tam1 do
          if(palavra2[i]==palavra1[i2])
            iguais = palavra2[i2]
            posicao = i
            break #Quero que saia desse laço e do outro
          end
        end
     end
   i+=1
  end
  • I believe you can do this by making use of a control variable. Basically, before you break forever, leave this variable in a "true" state, and break at the most superficial. The next one should parse this variable and break if it is true.

  • I made a control variable and it worked, but I didn’t understand your reasoning "leave this variable in a "true" state, and break into the shallowest one. The next one should parse this variable and break if it is true."

  • 1

    Basically, if you break all the loops, it’s true and each loop breaks. If not, only the first break runs, as it turns false.

1 answer

0


I believe the simplest solution in your case is to satisfy the condition of while:

if(palavra1[i]==palavra2[i2])
  iguais = palavra1[i2]
  posicao = i
  i = maior # sairemos dos laços aqui!
end

That said, I saw a solution in a question that pleased me enough - you can create a block catch instead of using the while:

catch:encerrar do
  5.times do |a|
    3.times do |b|
      throw :encerrar if a+b > 3
      puts "#{a}, #{b}\n"
    end
  end
end

throw stops execution of the entire block, so the condition if is satisfied.

Upshot:

resultado da execução do programa

Browser other questions tagged

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