Ruby for Loop

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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:

  1. for variable [, variable ...] in expression [do]  
  2.    code  
  3. end  

Ruby for loop using range

Example:

Output:

Ruby for 1

Ruby for loop using array

Example:

  1. x = ["Blue""Red""Green""Yellow""White"]   
  2. for i in x do   
  3.   puts i   
  4. end   

Output:

  Ruby for 2