Ruby

Print Array Ruby

An array is a collection of an ordered list of items known as elements. Arrays are vital building blocks in programming. They allow us to store multiple related values in a single variable, making the code easy to read.

Elements in an array can be of any time, including strings, integers, floats, hashes, nested arrays, and other Ruby objects.

This elaborate tutorial will help you understand how to work with Ruby arrays from the basics to array operations.

The Basics

Take an example code below that store’s information about users and their billing information.

user1_card_number = "4509 4285 4006 0689"
user2_card_number = "4922 0805 2092 4480"
user3_card_number = "4947 2643 4488 8995"

The example above stores credit card information in individual variables. If we have more than 100 users, the code becomes very hard to read and repetitive, and that’s where arrays come into play.

To create an array in Ruby, we give it a name and add the elements in a pair of square brackets separated by commas.

The following is an example:

card_info = [
    "4509 4285 4006 0689",
    "4922 0805 2092 4480",
    "4947 2643 4488 8995"
]

The code is more readable and easy to maintain as we only have a single variable to manage.

Printing Arrays

To print an array, you can use the puts method followed by the name of your array variable.

For example:

card_info = [
    "4509 4285 4006 0689",
    "4922 0805 2092 4480",
    "4947 2643 4488 8995"
]
puts card_info

Once we run the above program, it should print the elements stored in the array:

$ ruby arrays.rb
4509 4285 4006 0689
4922 0805 2092 4480
4947 2643 4488 8995

Accessing individual elements

We can access each element in an array by using its index. An index is like the position of the element in the entire array.

In Ruby, indexing starts at position 0. That means the first element in an array is at index 0.

To access the item at a specific index, we call the name of the array variable followed by the element’s index in a pair of square brackets as:

card_info = [
    "4509 4285 4006 0689",
    "4922 0805 2092 4480",
    "4947 2643 4488 8995"
]
puts card_info[1]

In this example, we access the second element in the array as:

$ ruby arrays.rb
4922 0805 2092 4480

If you access an index out of range of the array elements in Ruby, you will get nil as the return value.

For example, in the program below, the maximum index is 2. If we access an index higher than that, we should get nil as:

card_info = [
    "4509 4285 4006 0689",
    "4922 0805 2092 4480",
    "4947 2643 4488 8995"
]
card_info[5]
=> nil

Multi-Type Array

As we mentioned at the beginning of the tutorial, arrays can contain multiple data types.

For example, the following is an array with multiple element types.

personal_info = [
    "Alyssa King",
    "4947 2643 4488 8995",
    [
        "221B Baker Street",
        877
    ],
    32
]

The example above shows an array with multiple data types, including another array.

Suppose we want to access items inside a nested array, as shown above. In such a case, we first need to access the nested array using its index as:

personal_info[2]

Once we have the nested array, we can start accessing the elements using their corresponding indexes.

NOTE: Indexes in a nested array start at 0.

puts personal_info[2][0]

The example code above will print the value stored in the first index of the nested array.

Getting Array Length and Element Index

When working with a large array, it can be challenging to know how many elements are in it. You can use the length method to get the number of elements in the array.

puts personal_info.length
=> 4

The length method will return the actual number of elements in the array. However, remember the index of arrays starts at 0. Hence, the index of the last element in an array is:

array.length – 1

Let’s say you know the element stored in the array but not its index. To determine its index, you can use the index method as:

puts personal_info.index("Alyssa King")
=> 0

The method returns the index of the element if found.

Modifying Arrays

Now that we have created the array, how do we add or remove elements in the array?

Let’s take our initial card array:

card_info = [
    "4509 4285 4006 0689",
    "4922 0805 2092 4480",
    "4947 2643 4488 8995"
]

Adding Elements

There are several ways to add elements to an array.

# 1 – Using the next index

The first one is assigning the following index a value. For example, in the cards_info array, the following index is 3, we can set a value as:

card_info[3] = "4539 8298 7119 8259"

The above syntax will append a new element to the existing array items as:

puts card_info
=> ["4509 4285 4006 0689", "4922 0805 2092 4480", "4947 2643 4488 8995"]

#2 – Using push() method

It can be difficult to track the following index in an array, and assigning the wrong index will overwrite the existing element.

To avoid such a scenario, we can use the push method.

card_info.push("4532 7335 0011 9834")

The push method is beneficial as it automatically adds the element to the array, eliminating the need to worry about the index.

You can also use the left shift notation to add an element to the array. This method works similarly to the push method.

card_info << "4916 4324 7803 6973"

#3 – Using unshift() method

The push method adds elements at the end of the array. To add an element at the beginning of the array, we can use the unshift() method.

card_info.unshift("4645 8814 2354 1982")
=> ["4645 8814 2354 1982", "4509 4285 4006 0689", "4922 0805 2092 4480", "4947 2643 4488 8995"]

You will notice that the new element is at the beginning of the array.

Removing Elements

Ruby provides three ways to remove elements in an array.

#1 – Using the pop() method

The pop method is closely similar to the push method, except it removes the last element in the array.

card_info.pop
print card_info
["4509 4285 4006 0689", "4922 0805 2092 4480"]

#2 – Using the delete() method

The delete method finds all occurrences of the element you specify and removes them from the array.

Let us take another array that contains duplicates as:

db = [
    "MySQL",
    "PostgreSQL",
    "Fauna DB",
    "Neo4j",
    "Dynamo DB",
    "PostrgeSQL",
    "MySQL",
    "MongoDB"
]

In the example array, we have two duplicate elements. If we use the delete method and specify the “MySQL” element, the method will remove all the elements matching that value.

db.delete("MySQL")
print db

The resulting array is below:

["PostgreSQL", "Fauna DB", "Neo4j", "Dynamo DB", "PostrgeSQL", "MongoDB"]

#3 – Using the shift() method

As the name suggests, the shift method is similar to unshift. However, it removes the first element in the array.

db = [
    "MySQL",
    "PostgreSQL",
    "Fauna DB",
    "Neo4j",
    "Dynamo DB",
    "PostrgeSQL",
    "MySQL",
    "MongoDB"
]
db.shift
print db

The method will remove the first element and return the array as:

["PostgreSQL", "Fauna DB", "Neo4j", "Dynamo DB", "PostrgeSQL", "MySQL", "MongoDB"]

Iterating over an array

To iterate each item in the array, we can use each method.

db.each do |element|
    puts element
end

The above method returns each item in the array.

MySQL
PostgreSQL

MySQL
MongoDB

You can also use a for loop as shown:

for element in db do
    puts element
end

Conclusion

This guide taught you how to work with Ruby arrays, from the basics to an intermediate user. It is good to note that there are more to arrays beyond the scope of this guide. Consider the documentation to discover more.

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