Ruby Loops
Table of Contents
forloopswhileloopsuntilloopslooploops.timesiterator loop
A 'for' loop:
for i in 1..50
puts "#{i}"
endFor every number between 1 - 50
Using the inclusive
..operator tells the computer to include the last number in the loopWill
putsnumbers 1 - 50Using the exclusive
...operator tells the computer to exclude the last number from the loopWill
putsthe numbers 1-49Display the number on the console
Ends instructions for the loop
A 'while' loop:
i = 1
while i <= 50
puts "#{i}"
i += 1
endSets variable
iequal to oneWhile
iis less than or equal to 50, do the block of code (will print numbers 1 -50)Display the number on the console
Increment
iby one every time, that way the loop will end at some pointEnds instructions for the loop
An 'until' loop:
i = 1
until i > 50
puts "#{i}"
i += 1
endSets variable
iequal to oneUntil
iis greater than 50, run the block of code (will print numbers 1-50)Display
ion the consoleIncrement
iby one every time, that way the loop will end at some pointEnd the instructions for the loop
A 'loop' loop:
i = 1
loop do
puts "#{i}"
i += 1
break if i > 50
endSets variable
iequal to oneCreate a
loop, and run the block of codeDisplay
ion the consoleIncrement
iby one every time, that way the loop will end at some pointBreak the loop if
ibecomes greater than 50End the instructions for the loop
A '.times' iterator loop:
5.times do
puts "Hello world!"
endRun this loop five times, and do the block of code
Display the string on the console
End the instructions for this loop
Last updated
Was this helpful?