Loop Ruby

Estimated reading time: 1 minute

Loop / simple

loop do
  puts "This will keep printing until you hit Ctrl + c "
  #break
end
  • skip / break
i = 0
loop do
  i += 2
  if i == 4
    next        # skip rest of the code in this iteration
  end
  puts i
  if i == 10
    break
  end
end
# 2 6 8 10

while

x = gets.chomp.to_i

while x >= 0
  puts x
  x = x - 1
end

puts "Done!"

until

x = gets.chomp.to_i

until x < 0
  puts x
  x -= 1
end

puts "Done!"

for

x = gets.chomp.to_i

for i in 1..x do
  puts i
end

puts "Done!"

source

ruby