Ruby Array

Array Hash Keyword String Case Class Console Convert DateTime Exception File Format If Iterator Loop Math Method Nil Number Regexp Set Sort Split

Array

An array stores elements, one after another. In Ruby, the Array class is used to construct these linear collections. Arrays are a fundamental facet of this language. They are used everywhere.

New

This example uses an Array. It first constructs a new array with four integer elements. Then it modifies the first element (at index 0). We display the array values. They are stored in the specified order.

First element:The first element in an array is located at index 0, not 1. This is standard for most programming languages.

Based on:

Ruby 2

Ruby program that uses array

# An array of integers.
values = Array[10, 20, 30, 40]

# Modify the first element.
values[0] = 100

# Display the array.
puts values

Output

100
20
30
40

First, last

First

In life there is always a beginning and an end. This is true too in a Ruby array where at least one element exists. First and last are helpful methods. In a zero-element array, first and last return nil.

Info:The first array element is located at the index 0. And the last is located at the position equal to length minus one.

Ruby program that uses first, last

elements = ["ruby", "diamond", "gold"]

# First is the 0 index.
puts elements.first
puts elements[0]

# Last index is length minus one.
puts elements.last
puts elements[elements.length - 1]

Output

ruby
ruby
gold
gold

Mutable

Convert

Arrays are mutable. When we modify an element, no array copy is made. The element is simply replaced. In algorithms that change elements, these mutable arrays help improve speed. They are reused.

Sizing:Arrays are automatically resized. We have no need to specify how many elements will eventually be stored in them.

Terms:It is a topic of debate whether Array is technically a List. Often in languages, an Array is not resizable, but a list is.

Push

Plus

An array can have elements added or appended. The method we use for this is push(). The push() method adds the specified element value to the end of the array. In this example, we start with an empty array.

And:We add the string "tree" and then "grass" to the array. The first element is "tree" and the last is "grass."

Ruby program that uses push

# Create an empty array.
values = Array[]

# Push two elements.
values.push("tree")
values.push("grass")

# Print elements.
print "First: ", values.first, "\n"
print "Last:  ", values.last, "\n"

Output

First: tree
Last:  grass

Push, operator

Shift operator

This is an alternative syntax form to the push() method. It does the same thing, but requires fewer characters to type. The << operator can be chained—multiple elements can be added in a single statement.

Ruby program that uses append operator

items = Array[]
# Append two strings, one after another.
items << "cat" << "dog"
# Append another element.
items << "bird"

p items

Output

["cat", "dog", "bird"]

Delete

Exclamation mark

An array element can be deleted. When this occurs, the slot in the array is eliminated. Elements that come after are shifted forward. With delete_at(), we remove an element by specifying its index.

And:With delete(), we remove the first element of the specified value. We remove the "lime" element without knowing its index.

Ruby program that deletes elements

# Citrus fruits.
arr = Array["orange", "lemon", "lime"]

# Delete element at index 1.
arr.delete_at(1)
puts "Fruit:", arr

# Delete element with value of "lime".
arr.delete("lime")
puts "Fruit:", arr

Output

Fruit:
orange
lime
Fruit:
orange

Delete_if

Method

The delete_if method receives a block that evaluates to true or false. The block is tested against each element in the array. If it evaluates to true, the element is deleted. The block must be surrounded by curly brackets.

And:In the block, we supply a name for our element variable. I use "e." Here we delete all elements with values >= 40.

Ruby program that uses delete_if

# An array of integers.
numbers = [10, 20, 30, 40, 50]

# Delete numbers greater than or equal to 40.
numbers.delete_if {|e| e >= 40}
puts numbers

Output

10
20
30

Pop, empty

Program

The pop() method is the same as deleting the final element in an array. It simplifies the syntax for this operation. Here we create an array of three elements. We then pop it three times, yielding an empty array.

Tip:The final array element is removed each time pop() is called. The actual array is modified—no copy is created.

And:We see the "empty?" method on the array. This returns true if the array has zero elements, and false otherwise.

Ruby that pops an array

# Create and display an array.
names = Array["Conrad", "James", "Joyce"]
puts names, ""

# Pop the last element.
names.pop()
puts names, ""

# Pop again.
names.pop()
puts names, ""

# Pop again and see if the array is empty.
names.pop()
puts names.empty?

Output

Conrad   3 elements
James
Joyce

Conrad   2 elements
James

Conrad   1 element

true     0 elements

Each

Arrow indicates looping

Any loop can iterate over an array. But some methods, called iterators, make looping over an array more elegant. They reduce complexity. They reduce possible errors. We declare an iteration variable between two vertical bars.

Iterators

Tip:The each() method enumerates over each element in the array. Here we use the identifier "number" to access each element.

Ruby that uses each

# Some Wagstaff primes.
primes = [3, 11, 43, 683, 2731]

# Loop over primes and display them.
primes.each do |number|
    puts number
end

Output

3
11
43
683
2731

Each_index

Arrow indicates movement

Sometimes you want to access all indexes in an array. This can be done with a looping structure, like "for," but the each_index iterator is also available. It yields all the indexes of the array.

For Loop

Here:We use each_index over a three-element array. It has indexes 0, 1 and 2. We print them.

Ruby that uses each_index

# Array has indexes 0, 1 and 2.
values = ["cat", "dog", "sheep"]

# Loop over all indexes in the array.
values.each_index do |index|
    puts index
end

Output

0
1
2

Index

Index

Index searches an array for the specified element. It starts its search at the beginning and proceeds to the following elements. If it finds the element, it returns its index value.

Important:If index() does not find the specified element, it returns nil. This is a special object.

Nil
Ruby that uses index

items = ["Boots", "Cloak", "Dagger"]

# Get index of this element.
result = items.index("Cloak")
puts result

# Call index again.
result = items.index("Dagger")
puts result

# Call index with nonexistent element.
result = items.index("Helmet")
if result == nil
    puts "Not found"
end

Output

1
2
Not found

For

Loop

A for-loop iterates over a range of indexes.
In the range of the for-loop,
we can specify an array's lowest
and highest indexes. To loop over the entire array, we specify the highest valid index as the maximum of the range.

So:We start at zero. We progress to the inclusive maximum of the array's length minus one. We then access each element.

Lowercase i

A for-loop has many advantages over iterators such as each. You can use the index in the loop iteration for other operations. For example, you can access adjacent elements in the array.

And:This would be harder to do in more restrictive constructs that act on a single element at a time.

However:Using the simplest syntax possible for an operation is usually best. It leads to simpler, and thus higher-quality, programs.

Ruby that uses for-loop, array

# An array with four strings.
values = ["cat", "dog", "rabbit", "giraffe"]

# Loop over all indexes in the array.
for i in 0..values.length-1
    # Access the element.
    puts values[i]
end

Output

cat
dog
rabbit
giraffe

Uniq

Steps

The uniq method removes all duplicate elements from an array. We also can use the "uniq!" method to modify the array in-place. In this example, we call uniq to eliminate two duplicate element (a 1 and 4).

Remove Duplicates
Ruby that uses uniq

# Contains some duplicate elements.
values = [1, 1, 2, 3, 4, 4]

# Remove non-unique elements in-place.
values.uniq!
puts values

Output

1
2
3
4

Collect

Elements

The collect() method applies (maps) each element in an array to a new value based on a function. For example we can multiply each element by two. With "collect!" the array is modified in-place.

Map:In other languages like Python, the map() built-in has similar functionality as collect.

Block:The syntax for collect requires a block. In this code we use the identifier "e," but other identifiers work just as well.

Ruby that uses collect

# Contains three elements.
elements = [1, 0, 100]

# Use collect to multiply all elements by 2.
result = elements.collect{|e| e * 2}

# Display the result array.
p result

Output

[2, 0, 200]

Ranges

Range

With range syntax we can change parts of arrays in single operations. So we can replace a range of elements with a series of new elements (from a separate array). We can insert ranges this way.

Tip:Single elements too can be assigned. And often assigning one element at the time is easiest.

Ruby that assigns range of elements

elements = [10, 20, 30, 40, 50]
# Assign range of elements at indexes 1, 2, and 3 to a new array.
elements[1..3] = [100, 200]
puts elements

Output

10
100
200
50

Sort, reverse

Sort

Arrays have sort() and reverse() methods. With sort, we can specify a block to sort elements by a method. In this way we implement ascending and descending sort orders. We even handle class instance sorting.

Sort, reverse

Copy

Array

How can we copy an array? The slice syntax is helpful here. We take a total-array slice (with one of many possible syntax forms) and this returns, with little hassle, a copied array.

Copy Array

2D

2D array

We can create arrays of arrays,
2D arrays,
in Ruby. These are actually jagged arrays—each subarray can have a different length. We can use 2D array indexing syntax with these composite collections.

2D Array

Flatten:The flatten method converts a multidimensional array into one dimension. It copies all nested arrays.

Summary

Concept

Arrays are powerful. They are resizable and can be searched and tested. As a result, they are used in many Ruby programs. They often form of the basis of other classes and collections.

And:With array methods, we avoid repetitive code. This leads to clearer syntax forms and better programs.

Ruby