Ruby - Array Array

Introduction

In Ruby, you can represent ordered collections of objects using arrays.

Here's a basic array:

x = [1, 2, 3, 4] 

This array has four elements.

Each element is an integer, and is separated by commas.

Square brackets are used to denote an array literal.

Elements can be accessed by their index.

To access a particular element:

Demo

x = [1, 2, 3, 4] 
puts x[2]

Result

The indexing for Ruby's arrays starts from 0, so the first element of the array is element 0, and the second element of the array is element 1, and so on.

x[2] is addressing the third element of the array.

To change an element, you can simply assign it a new value or manipulate it:

Demo

x = [1, 2, 3, 4] 
x[2] += 1 
puts x[2]

Result

Or:

Demo

x = [1, 2, 3, 4] 
x[2] = "test" * 3 
puts x[2]

Result

Arrays don't need to be set up with predefined entries or have elements allocated manually.

You can create an empty array like so:

x = [] 

The array is empty, and trying to address, say, x[5] results in nil being returned.

You can add things to the end of the array by pushing data into it, like so:

x = [] 
x << "Word" 

After this, the array contains a single element: a string saying "Word".

With arrays, << is the operator for pushing an item onto the end of an array.

You can also use the push method, which is equivalent:

x.push("Word") 

You can remove entries from an array one by one.

Arrays act as a "last in, first out" system where items can be pushed onto the end but also popped from the end.

Popping is the process of retrieving and removing items from the end of the array.

Demo

x = [] 
x << "A" # from  ww  w .  j  a v a2s. c om
x << "B" 
x << "C" 
puts x.pop 
puts x.pop 
puts x.length

Result

You can join all the elements together into one big string by calling the join method on the array:

Demo

x = ["A", "B", "C"] 
puts x.join

Result

The join method can take an optional parameter that's placed between each element in the resulting string:

Demo

x = ["A", "B", "C"] 
puts x.join(', ')

Result

This time you join the array elements together, but between each set of elements you place a comma and a space.

Related Topics