...

/

Untitled Masterpiece

Learn to use arrays with the help of loops in Ruby.

The for loop with arrays

The individual values in an array are accessed through an index number. The for loop variable can be used as an index number. However, the array values can also be used directly in the for loop.

The following program demonstrates the various ways of accessing array elements:

Ruby
vals = [-5, 'Ruby', 3.8]
print("Using loop variable as an array index","\n")
for i in [0,1,2]
print(vals[i]," ")
end
print("\n")
print("Directly accessing the elements","\n")
for v in vals
print(v," ")
end
print("\n")
mix = ['a',1,2.5,'i',50,6,'m',4.4,6.7,'s','@educative']
print("Array index using \".length","\n")
for v in [0...mix.length]
print(mix[v]," ")
end

In the code above:

  • The first for loop accesses the array values with the help of the loop variable i.
  • The second for loop directly accesses the array values.
  • The third for loop accesses the array values with the help of loop variable, v, and the functions, ... and length.

The while loop with array

We usually use the while loop to deal with arrays when the number of iterations is not fixed. For a simple example, say we want to generate n terms of a Fibonacci sequence and store it in an array, where n is the user input. A Fibonacci sequence is a sequence in which each number is the sum of the two preceding ones, except the first two terms.

Let’s start by noting a few terms of this sequence: 0,1,1,2,3,5,8,13,21,34,0, 1, 1, 2, 3, 5, 8, 13, 21, 34, … ...