For loop

for iterates over each element of an array, string or range.

Recommendation

Review the Collections section to learn more about arrays and strings.

General structure#

for variable in collection
  instructions
Indentation

Instructions must have more left margin than the for line.

Over an array#

for n in [5 6 7 8 9 10]
  print n

items = ["Study" "Program" "Exercise"]
for item in items
  print "- " item

Over a string#

word = "Dino"

for letter in word
    print "Letter: " letter

Ranges#

A range generates a sequence of numbers. 1..10 goes up to 9; 1..=10 includes 10.

for i in 1..10  # From 1 to 9
  print i

for i in 1..=10 # From 1 to 10
  print i
First-class ranges

Ranges are values that you can assign to variables and use in expressions.

:print_range range
  for i in range
    print i

range = 1..10
print_range range