How to use the break statement inside two loops in Ruby?

4

When you execute the "break" command in "if" are you able 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
    
asked by anonymous 16.08.2018 / 20:08

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 solution that pleased me enough - you can create a block catch instead of using 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, as soon as the if condition is satisfied.

  

Result:

    
27.08.2018 / 06:09