Ruby - Array Array Type

Introduction

An array is a sequential collection of value where each item can be indexed.

In Ruby, a single array can contain items of mixed data types such as strings, integers, and floats or even a method call that returns some value.

For example, the final element in a1 shown here calls my method, array_length, which returns the length of the array, a0:

Demo

def array_length( anArray ) 
    return anArray.length 
end #   ww  w .  j a va 2  s.  c o m

a0 = [1,2,3,4,5] 
a1 = [1,'two', 3.0, array_length( a0 ) ]  
p( a1 ) #=>[1, "two", 3.0, 5]

Result

The first item in an array has the index 0.

The final item has an index equal to the total number of items in the array minus 1.

Given the array a1, this is how to obtain the values of the first and last items:

a1[0]        # returns 1st item (at index 0)  
a1[3]        # returns 4th item (at index 3)  

Related Topic