Home
Search
Array ExamplesUse arrays: add elements, change elements and test arrays with loops and iterators.
Ruby
This page was last reviewed on Oct 25, 2022.
Array. A Ruby array is a list that grows as we add elements. The runtime handles the low-level details, so we can write clearer and more bug-free programs.
Shows an arrayShows an array
Array creation. To create a Ruby array, we use the Array class. We can omit "Array" and just use the initializer. Or we can assign each element as we go along.
String Arrays
New Array. We first construct a new array with 4 integer elements. Then we modify 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.
Shows an array
# An array of integers. values = Array[10, 20, 30, 40] # Modify the first element. values[0] = 100 # Display the array. puts values
100 20 30 40
First, last. There is always a beginning and an end. This is true in an array where at least one element exists. First and last are helpful methods.
Warning In a zero-element array, first and last return nil. So we must check the result if our array may be empty.
Info The first array element is located at the index 0. And the last is located at the position equal to length minus one.
Shows an array
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]
ruby ruby gold gold
Push. This method adds the specified element value to the end of the array. This is possible with a mutable collection. Here we start with an empty array.
And We add the string "tree" and then "grass" to the array. The first element is "tree." The last is "grass."
# 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"
First: tree Last: grass
Push, operator. This is an alternative to the push method. It does the same thing but requires less source code. The << operator can be chained. Many elements can be added in one statement.
items = Array[] # Append two strings, one after another. items << "cat" << "dog" # Append another element. items << "bird" p items
["cat", "dog", "bird"]
Delete. An array element can be deleted. When this occurs, the slot in the array is eliminated. Elements that come after are shifted forward.
Delete_at With delete_at(), we remove an element by specifying its index. No search is required.
Delete With delete(), we remove the first element of the specified value. We remove the "lime" element without knowing its index.
# 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
Fruit: orange lime Fruit: orange
Delete_if. This 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.
Block The block must be surrounded by curly brackets. In the block, we supply a name for our element variable.
Here I use "e." Another name like "x" could instead be used. The expression deletes all elements with values >= 40.
# 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
10 20 30
Pop, empty. The pop method deletes the final element in an array. It simplifies the syntax for this operation. Empty(), also shown, returns true if an array has zero elements.
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.
# 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?
Conrad 3 elements James Joyce Conrad 2 elements James Conrad 1 element true 0 elements
Each. 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.
Syntax We declare an iteration variable between two vertical bars. It is important to learn the syntax here.
Tip Each() enumerates over each element in the array. Here we use the identifier "number" to access elements.
# Some Wagstaff primes. primes = [3, 11, 43, 683, 2731] # Loop over primes and display them. primes.each do |number| puts number end
3 11 43 683 2731
Each, short syntax. Ruby is known for its expressive, glittering syntax. Here we use a short syntax form to write an iterator on one line.
Tip We omit the "do" keyword and use curly brackets. This style makes it harder to add more statements.
# Some even numbers. # ... Let's get even. evens = [2, 4, 6, 8] # Use short syntax form for the iterator block. evens.each {|ev| puts ev}
2 4 6 8
Each_index. Sometimes we want to access all indexes in an array. This can be done with a loop, but the each_index iterator is also available. It yields all the indexes of the array.
While, Until
Here We use each_index over a three-element array. It has indexes 0, 1 and 2. We print them.
# 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
0 1 2
Index. This 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
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
1 2 Not found
For-loop. In the range of the for-loop, we can specify an array slowest 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.
Advantages With a for-loop, we can use the index in the loop iteration for other operations. We can access adjacent elements in the array.
Usually The simplest syntax possible for an operation is best. This leads to simpler (and thus higher-quality) programs.
# 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
cat dog rabbit giraffe
Uniq. This removes all duplicate elements. 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).
Duplicates
# Contains some duplicate elements. values = [1, 1, 2, 3, 4, 4] # Remove non-unique elements in-place. values.uniq! puts values
1 2 3 4
Collect. This 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.
# 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
[2, 0, 200]
Ranges. 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. We can insert ranges this way.
Tip Single elements too can be assigned. And often assigning one element at the time is easiest.
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
10 100 200 50
Mutable. 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.
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.
Include. The "contains" method on arrays is called "include?" in Ruby. This method returns true or false (it is a predicate method).
Include
Sort, reverse. 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.
Sort
Reverse
Copy. How can we copy an array? The slice syntax is helpful here. We take a total-array slice. And this returns (with little hassle) a copied array.
Copy Array
Two-dimensional. We can create arrays of arrays—2D arrays. These are jagged arrays. Each subarray can have a different length. We can use 2D array indexing syntax here.
2D Array
A summary. Ruby arrays are powerful: they are resizable, and can be searched. As a result, they are used in many Ruby programs, forming the basis of other classes and collections.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 25, 2022 (edit link).
Home
Changes
© 2007-2022 Sam Allen.