Ruby for Loop

Ruby for loop iterates over a specific range of numbers. Hence, for loop is used if a program has fixed number of iterations.

Ruby for loop will execute once for each element in expression.

Syntax:

for variable [, variable ...] in expression [do]  

   code  

end

Ruby for loop using range

Example:

a = gets.chomp.to_i   

for i in 1..a do   

  puts i   

end

Output:

Ruby for 1

Ruby for loop using array

Example:

x = ["Blue", "Red", "Green", "Yellow", "White"]   

for i in x do   

  puts i   

end

Output:

Ruby for 2

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *