Loops

While Loop

i = 1
while i <= 5
  puts i
  i += 1
end
  • Runs while condition is true.
    Output:
1
2
3
4
5

For Loop

for n in 1..5
  puts n
end
  • 1..5 means range from 1 to 5.
    Output: 1 2 3 4 5

Each Loop

[1, 2, 3, 4, 5].each do |num|
  puts num * 2
end
  • Iterates over each element.
    Output:
2
4
6
8
10

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *