Ruby Loops
Table of Contents
for
loopswhile
loopsuntil
loopsloop
loops.times
iterator loop
A 'for' loop:
for i in 1..50
puts "#{i}"
end
For every number between 1 - 50
Using the inclusive
..
operator tells the computer to include the last number in the loopWill
puts
numbers 1 - 50Using the exclusive
...
operator tells the computer to exclude the last number from the loopWill
puts
the 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
end
Sets variable
i
equal to oneWhile
i
is less than or equal to 50, do the block of code (will print numbers 1 -50)Display the number on the console
Increment
i
by 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
end
Sets variable
i
equal to oneUntil
i
is greater than 50, run the block of code (will print numbers 1-50)Display
i
on the consoleIncrement
i
by 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
end
Sets variable
i
equal to oneCreate a
loop
, and run the block of codeDisplay
i
on the consoleIncrement
i
by one every time, that way the loop will end at some pointBreak the loop if
i
becomes greater than 50End the instructions for the loop
A '.times' iterator loop:
5.times do
puts "Hello world!"
end
Run 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?