colors = ["red", "green", "blue"]
for color in colors
puts color
endTwo-variable form gives index, value:
for i, color in colors
puts "#{i}: #{color}"
endSingle-variable form gives keys:
config = {"host" => "localhost", "port" => 3000}
for k in config
puts k
end
# prints host, portTwo-variable form gives key, value:
for k, v in config
puts "#{k} = #{v}"
endIterate from 0 to N-1:
for i in 5
puts i
end
# prints 0, 1, 2, 3, 4Use range(start, end) to iterate from start to end-1:
for i in range(3, 7)
puts i
end
# prints 3, 4, 5, 6range() also works as a standalone function that returns an array:
arr = range(5)
# arr is [0, 1, 2, 3, 4]Stop the loop early:
for n in [1, 2, 3, 4, 5]
if n == 4
break
end
puts n
end
# prints 1, 2, 3Skip to the next iteration:
for n in [1, 2, 3, 4, 5]
if n % 2 == 0
next
end
puts n
end
# prints 1, 3, 5break and next work in while loops too.
Next: Collection Methods