Ruby's for loop works on a list of items, and it iterates over them, one by one.
For example, here is a for loop that iterates over the items in an array, displaying each in turn:
for i in [1,2,3] do puts( i ) end
The for loop is more like the "for each" iterator.
The items over which the loop iterates don't have to be integers. This works just as well:
for s in ['one','two','three'] do puts( s ) end
Ruby for is "syntax sugar" for the each method, which is implemented by collection types such as Arrays, Sets, Hashes, and Strings.
This is one of the for loops shown earlier rewritten using the each method:
[1,2,3].each do |i| puts( i ) end
The following examples shows how similar for loops are to each iterators.
# --- Example 1 --- # i) for # w ww.j av a2 s . c om for s in ['one','two','three'] do puts( s ) end # ii) each ['one','two','three'].each do |s| puts( s ) end # --- Example 2 --- # i) for for x in [1, "two", [3,4,5] ] do puts( x ) end # ii) each [1, "two", [3,4,5] ].each do |x| puts( x ) end
The do keyword is optional in a for loop that spans multiple lines, but it is obligatory when it is written on a single line:
# Here the 'do' keyword can be omitted for s in ['one','two','three'] puts( s ) # w w w .j a va 2 s.co m end # But here it is required for s in ['one','two','three'] do puts( s ) end
This example shows how both for and each can be used to iterate over the values in a range:
# for for s in 1..3 puts( s ) # www. j a va 2 s . co m end # each (1..3).each do |s| puts(s) end