MC logo

For Loop

  Ruby Example Code

<<While Loop for1.rb Case Expression>>
# Simple for loop using a range.
for i in (1..4)
    print i," "
end
print "\n"

for i in (1...4)
    print i," "
end
print "\n"

# Running through a list (which is what they do).
items = [ 'Mark', 12, 'goobers', 18.45 ]
for it in items
    print it, " "
end
print "\n"

# Go through the legal subscript values of an array.
for i in (0...items.length)
    print items[0..i].join(" "), "\n"
end
See:Ruby User's GuideRuby Manual

The Ruby for loop is similar to the Python for or the perl foreach. Its basic operation is iterate over the contents of some collection. This may be an actual array or a range expression. A range expression is two numbers, surrounded by parens, and separated by either two dots or three. The three-dot form omits the last number from the range, while the two-dot version includes it. The three-dots version can be quite useful for creating a range of legal subscripts since the array size is not a legal subscript.
<<While Loop Case Expression>>