Programming Fundamentals/Loops/Ruby

loops.rb

edit
# This program demonstrates While, Do, and For loop counting using
# user-designated start, stop, and increment values.
#
# References:
#     https://en.wikibooks.org/wiki/Ruby_Programming

def get_value(name)
    puts "Enter " + name + " value:"
    value = gets.chomp.to_i
    return value
end

def while_loop(start, stop, increment)
    puts "While loop counting from " + start.to_s + " to " + 
        stop.to_s + " by " + increment.to_s + ":"
    count = start
    while count <= stop
        puts count
        count = count + increment
    end
end

def do_loop(start, stop, increment)
    puts "Do loop counting from " + start.to_s + " to " + 
        stop.to_s + " by " + increment.to_s + ":"
    count = start
    begin
        puts count
        count = count + increment
    end while count <= stop
end

def for_loop(start, stop, increment)
    puts "For loop counting from " + start.to_s + " to " + 
        stop.to_s + " by " + increment.to_s + ":"
    for count in (start).step(stop, increment)
        puts count
    end
end

def main()
    start = get_value("starting")
    stop = get_value("ending")
    increment = get_value("increment")

    while_loop(start, stop, increment)
    do_loop(start, stop, increment)
    for_loop(start, stop, increment)

    return 0
end

main()

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own Ruby compiler / interpreter / IDE.

See Also

edit