Ruby Array

Array Hash String Case Class 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 arrays. We modify, test and use arrays in many program contexts. Arrays are an important, fundamental type.

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 a Ruby array is located at index 0, not 1. This is standard for most programming languages.

Based on:

Ruby 2.0.0

Program that uses array: Ruby

# 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

Mutable

Convert

Arrays are mutable. We modify an element and no array copy is made—the element is simply replaced. This makes arrays an important optimization. In algorithms that change elements, arrays help improve speed.

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

Note: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."

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

Program that uses push: Ruby

# 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

Delete

Shift operator

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.

Program that deletes elements: Ruby

# 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, a computer program unit

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.

Program that uses delete_if: Ruby

# 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.

Program that pops an array: Ruby

# 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.

Program that uses each: Ruby

# 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.

Program that uses each_index: Ruby

# 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 in Ruby.

Nil
Program that uses index: Ruby

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.

Program that uses for-loop, array: Ruby

# 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
Program that uses uniq: Ruby

# 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

Summary

Concept

Arrays in Ruby 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.

Class

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

Ruby