Control Flow

For Loop in Ruby

To run a block of code a specified number of times


Syntax
#range is represented as lower_limit..upper_limit
for x in range
    #run code from lower limit to upper limit of range
    #x keeps track of which iteration
end

Notes

The for loop is typically used when the number of needed iterations is known.


Example
#fizzbuzz exercise, iterating from 1 to 100
for x in 1..100
    word = nil
    if x % 15 == 0
        puts "fizzbuzz"
    elsif x % 3 == 0
        puts "fizz"
    elsif x % 5 == 0
        puts "buzz"
    else
        puts "fizzbuzz"
    end
end

See Also
Documentation

Ruby Tutorial - Loops

Add to Slack

< Case Statement   |   For Each >

© 2019 SyntaxDB. All Rights Reserved.