Loops run the same code many times with different data — Ruby gives you a low-level while and a family of elegant iterators.
1 while
Repeats as long as a condition stays true — check first, run after.
2 times
3.times { } runs a block exactly three times, counting from 0.
3 each
Walks a collection and hands you one element per pass.
4 upto
1.upto(5) counts up number by number.
5 break
Bail out of any loop the moment you are done.
Repeat without repeating yourself
while1Repeats as long as a condition stays true — check first, run after.
times23.times { } runs a block exactly three times, counting from 0.
each3Walks a collection and hands you one element per pass. upto41.upto(5) counts up number by number. break5Bail out of any loop the moment you are done. 5 building blocks make up Repeat without repeating yourself
A while loop re-checks its condition every pass; iterators yield one value at a time.
Console
output appears as the program runs…
Click a tool, then click what it does to lock the pair.
6 conceptsTap a card to expand ?whiledrops into place
?timesdrops into place
?eachdrops into place
?uptodrops into place
?breakdrops into place
?loop dodrops into place
A classic accumulator loop — and a sneaky look at what n is afterwards.
Your predicted output — one line per console line
Hint: The loop adds 1 + 2 + 3 + 4 into total. It exits only after the check fails — and by then n had already been bumped to 5.
Every while pass takes the same four-step journey — until the check says no.
01while repeats until its condition turns false — re-checked every pass.
02Something in the body must move the condition toward false, or you loop forever.
03times counts from 0; upto counts from the start number and includes the end.
04each visits every element of a collection, one pass per element.
05break exits any loop immediately.