"while" and "until" loops?


#1

i don't understand what "while" and "until" loops are and what they do. I passed the lesson by basically copying the lesson showing what to do, but i'm completely confused as to what this is.


#2

I passed the lesson by basically copying the lesson showing what to do

That's your problem. Before moving on to another concept, it's critical to understand the one presented.

while and until are keywords, they're used to repeat a code a certain number of times. The loops stop when a certain condition is met. while will keep doing the code as long as a condition is true/false, and until will keep doing the code until (:smile:) a condition is true/false.

For example, if you want to print "Hello" 5 times, you could do:

i = 0
while (i < 5)
puts "Hello"
i += 1
end

#3

i think i get the concept, but i dont understand why you do "i=0" and "while (i<5)" and "1+=1" and all that..


#4

Well then you don't really understand the concept then. You might think you understand it, but if you're not able to explain it (even only to yourself), then you don't understand it.

The idea is to be able to repeat code. Of course we don't want to repeat the code indefinitely, we want to be able to choose how many times to repeat it.

That's why we need to use a limit, a condition (in my example, the limit will be based on the value of an integer, the variable i, but you can use any condition you want).

First we initialize our i to 0 OUTSIDE of the loop (so that we know where we start from):

i = 0

Then we set the condition INSIDE the loop (so that we know when to stop):

while (i < 5)

Then we increment our i value INSIDE the loop so that we can reach the condition at least once (otherwise we would have an infinite loop):

i += 1

Of course we also add the action we want to repeat INSIDE the loop, otherwise our loop is pointless:

puts "Hello"

#5

i=0 is basically the first condition set .There after the next instruction "while (i<5)" means as long as "i" is less than 5 we will print our message "Hello".But this would go on forever as i=0 which is definately less than five and will stay that way unless we change it.So to avoid this we must give a condition that will stop the code from running at some point.This is done by increasing "i" by one each time which is represented as i += 1 ..Ps "i was set to zero(i=0)".When "i" is increased plus one until its more than five the code stops running.


#6

Which is better:

makeSoup while !ingredients.empty?
makeSoup until ingredients.empty?

while and until do the same thing, one is just "nicer" to read in some instances.

From: harbichidian see for more information Stackoverflow