Ruby

Add to Array in Ruby

When it comes to storing related and non-complex information in a program, arrays always come up. Arrays are a collection of an ordered list of items. Using arrays, you can store related values in a single variable, making your code efficient and easy to manage. In Ruby, arrays contain lots of built-in methods, making working with list data much more effortless.

This article describes various methods you can use to add items to an array in Ruby.

How to Create An Array In Ruby

In Ruby, there are a few ways to create an array. The most common and basic way is by adding the array elements in a pair of square brackets separated by a comma.

[1,2,3,4,5]

The above is an array containing five elements.

Like any other valid object, you can assign an array to a variable name as:

myarry = [1,2,3,4,5]

To create an empty array using the square brackets method, you can do:

empty = []

The above syntax will initialize an empty array, and you can append values using the methods we will discuss in the next section of this tutorial.

Another way to create an array in Ruby is to use the new class method.

myarray = Array.new

The above format will create an empty array. This format is similar to initializing an empty array using an empty pair of square brackets.

To specify the size of the array during creation, you pass the size inside a pair of parenthesis:

myarray = Array.new(10)

In the above example, Ruby creates an array of size 10 elements, which means the index of the elements will start from 0 to 9.

The final way to create an array combines both the square brackets and the new class method.

The syntax for that is below:

myarray = Array.[]()

The above syntax will create a new empty array. If you want to assign values during array creation, you can do:

myarray = Array.[](1,2,3,4,5)

Ruby will take the elements passed inside the parenthesis and add them to the new array.

How to Add Elements to an Array in Ruby

If you have an existing array, you can add elements to the collection using various techniques.

Method #1: Using the Next Index

The first way is to assign a value to the following index. Take an example where you have an array such as the one shown below:

frameworks = [
   "React",
   "Angular",
   "Vue JS",
   "Svelte"
]

In the above example, we have four elements in the array. Since the index of the array, elements start at 0, the maximum index value is 3.

To add an element to the array using its index, we can assign a value to the subsequent index as:

frameworks[4] = "Mithril Js"

There are two disadvantages to using the above technique to add items to an array.

One: If you have a large array, it can be challenging to recall the consequent index. Thus, if you skip an index, Ruby will insert nil values until the matching index.

For example:

frameworks[10] = "Stencil Js"
print frameworks
["React", "Angular", "Vue JS", "Svelte", "Mithril Js", nil, nil, nil, nil, nil, "Stencil Js"]

In the example above, Ruby adds nil values from index 5 to 9 to match the specified index 10.

Two: If you specify the wrong index, you will overwrite the value at the specified index.

For example:

frameworks = [
   "React",
   "Angular",
   "Vue JS",
   "Svelte"
]
frameworks[1] = "Ooops!"
print frameworks

In the example above, we specified the wrong index, leading to an overwrite to the stored value.

Here is an output to show this:

["React", "Ooops!", "Vue JS", "Svelte"]

Method #2: Using the push method

We can use the built-in push method to avoid errors that may arise from using the previous technique.

The method will take the specified value in the parenthesis and add it to the last item in the array.

frameworks = [
   "React",
   "Angular",
   "Vue JS",
   "Svelte"
]
frameworks.push("Mithril Js")

Using the push method, you do not need to recall the current index; Ruby takes care of that automatically.

In some cases, you will find the << syntax used instead of the push method. The functionality is identical to the push method as:

frameworks << "Mithril Js"

Method #3: Using the Unshift Method

Both the index and push methods append elements to the end of the array. To add an element at the beginning of the collection, use the unshift method.

The unshift method works similarly to the push method. However, it adds the element at index 0.

frameworks = [
   "React",
   "Angular",
   "Vue JS",
   "Svelte"
]
frameworks.unshift("Mithril Js")
print frameworks

The resulting array for this example will be:

["Mithril Js", "React", "Angular", "Vue JS", "Svelte"]

Method #4: Using the Insert Method

The #insert method in Ruby accepts an index position and a value as the arguments. You can use it to insert an element at any index position.

Consider the following syntax:

frameworks = [
   "React",
   "Angular",
   "Vue JS",
   "Svelte"
]
frameworks.insert(2, "Stencil Js")
print frameworks

The resulting array for this example is:

["React", "Angular", "Stencil Js", "Vue JS", "Svelte"]

In the example above, the insert method will “squeeze” the element into the specified array.

NOTE: Use this method cautiously, especially if you have other code blocks referencing the set index.

Conclusion

This tutorial has shown you how to work with arrays, including using various methods to create and add items to an array.

PRO TIP: Ruby has aliases for the push and unshift methods as append and prepend, respectively.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list