[ENGLISH VERSION] Loops #1

Hey, are you ok?

As fundamental part of the programming languages, the loops allow us repeat a wide range of commands, saving work/time, being an important tool for all programmer.

Ruby offers many of them and today we’re going to talk about three: loop, while and until.


LOOP

Pretty basic, loop needs a block and a stop condition (explicit break), because this one can take us to the infinity only because it wants to.

x = 0

loop do
  x += 1
  puts x
  break if x >= 5
end

Out:

1
2
3
4
5

Notice that loop doesn’t inform a block variable, like others … take a test!

x  = 0
loop do |i|
  p i
  x += 1
  break if x >= 10
end

WHILE

Well known, while does something “while” it’s codition is satisfied.

y = 1

while y <= 10
  puts y
  y += 1
end

Out:

1
2
3
4
5
6
7
8
9
10

The while loop, like all others, accepts the break command, but be careful – you don’t really need it, if you make a good loop logic.


UNTIL

The until loop executs a set of commands “until” – Ruby is such a human language – it’s condition is satisfied, the opposite of while.

a = 1

until a >= 10
  puts a
  a += 1
end

Out:

1
2
3
4
5
6
7
8
9

So, did you like this post? Is something missing? Tell on the comments!

It was so good to see you here! Bye!

ENGloops1

Anúncios

Um comentário sobre “[ENGLISH VERSION] Loops #1

Diga alguma coisa ... suas dúvidas quem sabe!

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair / Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair / Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair / Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair / Alterar )

Conectando a %s