Coding Ruby

Work with Arrays in Ruby


Work with Arrays in Ruby


  • An array is a form of data structure that represents a listing of values, known as elements.
  • Arrays allow you to store multiple values in a very single variable. This could condense and organize your code, creating it additional legible and reparable. Because arrays area unit objects with their own ways, they will build operating with lists of information abundant easier.
  • Arrays will contain any data type, together with numbers, strings, and different Ruby objects.
  • Let’s cross-check a straightforward example of however powerful arrays is. Imagine you had to keep up a listing of email addresses. while not associate array, you would possibly store email addresses in variables, like this:
email1 = "[email protected]"
email2 = "[email protected]"
email3 = "[email protected]"
email4 = "[email protected]"
  • This approach is tedious and might quickly become troublesome to keep up, as it is not terribly versatile. Adding another email address suggests that you’d need to add, and track an extra variable.
  • If you employ associate array, you’ll be able to change this data:
  • Instead of making 5 separate variables, you currently have one variable that contains all four email addresses. During this example, we have a tendency to used square brackets [ ] — to make an associate array and separated every entry with a comma.
  • If you had to feature an extra email address, you’d add another email address to the array instead of making and managing a replacement variable.
  • To access a selected item or part of an associate array, you reference its index or its position within the array. In Ruby, indexes begin at 0. Therefore to retrieve the primary elements from our emails array, we have to append the element’s index to the variable exploitation square brackets, like this:
print emails[0];


[email protected]

In this tutorial, you may produce arrays, access the values they contain, add, modify, and remove elements in the associated array, and reiterate through the elements in an array to resolve additional advanced issues. Let’s begin by observing the way to produce arrays in additional detail.

Create an Array

  • To produce an associate array in a very Ruby program, use square brackets: ([ ]), and separate the values you would like to store with commas.
  • For example, produce an array of sharks and assign it to a variable, like this:
sharks = ["Hammerhead", "Great White", "Tiger"]

You can print out an entire array with the print statement, which will display the array’s contents:

print sharks


["Hammerhead", "Great White", "Tiger"] 

If you would like to make associate array wherever every entry could be a single word, you’ll be able to use the %w{} syntax, that creates a word array:

days = %w{Monday Tuesday Wednesday Thursday Friday Saturday Sunday}

This is like making the array with square braces:

days =  ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
  • However, notice that the %w{} technique allows you to skip the quotes and also the commas.
  • Arrays area unit typically to cluster along lists of comparable knowledge varieties, however in Ruby, arrays will contain any worth or a combination of values, together with different arrays. Here’s associate example of associate array that contains a string, a nil value, an integer, associated an array of strings:
record = [

Now let’s cross-check however we have a tendency to access knowledge hold on in arrays.

Accessing items in Arrays

  • You access an associated item in a very Ruby array by pertaining to the index of the item in square brackets.
  • Let’s explore this idea with our array of sharks, assigned to the variable sharks:
sharks = ["Hammerhead", "Great White", "Tiger"]

The sharks array has 3 parts. Here could be a breakdown of however every part within the sharks array is indexed.

READ  Python algorithm - Breadth First Traversal or BFS for a Graph
Hammerhead Greate White Tiger
O 1 2

The 1st element within the array is Hammerhead, that is indexed at zero. The last part is Tiger, that is indexed at 2. The count starts with zero in indices, which fits against our natural intuition to begin the investigation at one, therefore you will need to stay this in mind until it becomes natural.

Note: It’d assist you to think about the index as an associate offset; it is the variety of places from the beginning of the array. the primary part is at the start, therefore its offset, or index, is 0. The second part is one spot aloof from the primary entry within the array, therefore its offset, or index, is 1.

You will ascertain what number parts area unit in the associated array with the length technique.




Although the indices of sharks begin at zero and visit 2, the length property returns the number of elements within the array, which is 3. It is not involved with the indices in the least.

If you needed to search out out the fact of a selected element in the associated array, like a seahorse, use the index() method:

print sharks.index("Tiger")



This returns the index of the primary element containing that text. If the index isn’t found, like for a value that doesn’t exist, the console can return nil.

print sharks.index("Whale")



To get the last element of the associated array in Ruby, use the index -1:

print sharks[-1]



Ruby conjointly provides the primary and last ways to induce the primary and last elements without indices:

puts sharks.first
puts sharks.last



Attempting to access an index that doesn’t exist will return nil.




Arrays will contain different arrays, that we have to call nested arrays. This is often a technique to model two-dimensional knowledge sets in a program. Here’s an associate example of a nested array:

nested_array = [

In order to access elements in a nested array, you’d add another index to correspond to the inner array. For instance, to retrieve the value coral from this nested array, you’d use the subsequent statement:

print nested_array[1][0];



In this instance, we have a tendency to accessed the array at position 1 of the nested_array variable, that nested array [“coral”, “reef”]. We have a tendency to then accessed the weather element at position 0 of that array, that was “coral”.

Now let’s cross-check the way to add elements to associate array.

Add Elements

We have 3 elements in our sharks array, that area unit indexed from 0 to 2:

sharks = ["Hammerhead", "Great White", "Tiger"]

There area unit many ways that to feature a replacement element. You’ll assign a worth to consequent index, that during this case would be 3:

sharks[3] = "whale";

print sharks


["Hammerhead", "Great White", "Tiger", "Whale"] 

This technique is error-prone although. If you add a component associated accidentally skip an index, it’ll produce a nil element within the array.

sharks[5] = "Sand";

print sharks;


["Hammerhead", "Great White", "Tiger", "Whale", nil, "Sand"]

Access extra array element which returns the nil value




Finding consequent accessible index in the associated array is erring and takes beyond regular time. Avoid errors by exploitation the push technique, that adds a component to the end of the array:

print sharks


["Hammerhead", "Great White", "Tiger", "Whale", nil, "Whale", "Thresher"]

You also can use the << syntax rather than the push technique to feature element to the end of

sharks << "Bullhead"


["Hammerhead", "Great White", "Tiger", "Whale", nil, "Whale", "Thresher", "Bullhead"]

To add an element to the start of the array, use the unshift() method:

print sharks


["Angel", "Hammerhead", "Great White", "Tiger", "Whale", nil, "Whale", "Thresher", "Bullhead"]

let’s cross-check removing them.

READ  Use Array Methods in Ruby

Remove Elements

To take away a particular element from an array, use the delete or delete_at ways. Within the sharks array, we tend to accidentally create a nil array element earlier. Let’s get obviate it.

First, notice its position within the array. You’ll use the index technique to try and do that:

print sharks.index(nil)



Then use delete_at to get rid of the element at index 4 and print the array:

print sharks


["Angel", "Hammerhead", "Great White", "Tiger", "Whale", "Thresher", "Bullhead"]

The delete technique removes the element from an array that matches the value you pass in. Use it to get rid of Whale from the array:

print sharks;


["Angel", "Hammerhead", "Great White", "Tiger", "Thresher", "Bullhead"]

The delete technique can take away all occurrences of the value you pass, thus if your array has duplicate elements, they’re going to all be removed.

The pop technique can take away the last element in the array.

print sharks;


["Angel", "Hammerhead", "Great White", "Tiger", "Thresher"]

Bullhead has been removed because of the last element of the array. So as to get rid of the primary element of the array, use the shift technique.

print sharks


["Hammerhead", "Great White", "Tiger", "Thresher"]

This time, Angel was aloof from the start of the array.

By mistreatment pop and shift, you’ll take away elements from the start and therefore the finish of arrays. Using pop is most popular where likely because the remainder of the things within the array retain their original index numbers.

The delete_at, pop, and shift ways all modification the initial array and come back the part you deleted. Do this example:

sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
deleted_at_element = sharks.delete_at(1)
popped_element = sharks.pop

puts "Deleted_at element: #{deleted_at_element}"
puts "Popped element: #{popped_element}"

puts "Remaining array: #{sharks}"


Deleted_at element: Great White
Popped element: Whale
Remaining array: ["Hammerhead", "Tiger"]

You currently understand many ways in which to get rid of components from an array. Currently, let’s cross-check a way to modify the element we tend to have already got.

Modify Existing Element

To update the element within the array, assign a brand new value to the element’s index by mistreatment the assignment operator, a bit like you’d with a regular variable.

Given a brand new array of sharks, with “Hammerhead” at index 0, let’s replace “Hammerhead” with “Angel”:

sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
sharks[0] = "Angel"
print sharks;


["Angel", "Great White", "Tiger", "Whale"]

To check that you update the proper element, you’ll use the index technique to find the element initial, a bit like you probably did to search out the element you wished to delete.

READ  C program to delete an element from an array

Now let’s cross-check a way to work with all of the weather within the array.

Iterating Over Array

Ruby provides many ways to tell over an array, and every technique you utilize depends on the type of labor you wish to perform. During this article, we’ll explore a way to tell over an array and show every one of its components.

Ruby provides the syntax, that appears like this:

sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
for shark in sharks do
  puts shark

Here’s however it works. For every element within the sharks array, Ruby assigns that part to the native variable shark. We are able to then print the element’s value mistreatment puts.

You will not see fairly often although. Ruby arrays are objects, and that they offer the each technique for operating with elements. The each technique works in an exceedingly similar fashion to, however, incorporates a totally different syntax:

sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
sharks.each do |shark| 
  puts shark


Great White

The each technique uses a syntax you will see typically in Ruby programming. It takes a Ruby block as its argument. A block is a few codes which will be dead later within the context of the strategy. During this case, the code is puts shark. The shark keyword, capsulate within the pipe characters ( | ), is that the native variable that represents the part within the array that the block can access. Ruby assigns the part to the present variable and executes the code within the block. The each technique repeats this method for every part within the array. The result appears like this:

When the block is simply one line, you frequently see Ruby developers replace the do and end keywords with curling braces and condense the entire statement into one line, like this:

sharks.each {|shark| puts shark }

This produces similar results, however, uses fewer lines of code.

The each_with_index technique works in an exceedingly similar manner, however, it additionally provides you with access to the index of the array element. This program uses each_with_index to print out the index and therefore the worth for every element:

sharks = ["Hammerhead", "Great White", "Tiger", "Whale"]
sharks.each_with_index do |shark, index| 
  puts "The index is #{index}"
  puts "The value is #{shark}"

For every element within the array, Ruby assigns the part to the variable shark, and assigns the present index to the index variable. We are able to then reference each of these variables within the block.

The results of this program appear like this:


The index is 0
The value is Hammerhead
The index is 1
The value is Great White
The index is 2
The value is Tiger
The index is 3
The value is Whale

You’ll integrate over the elements in the array type in your own programs, like once you got to show the things from a database on an internet site, or once you are reading lines from a file and process their contents.


Arrays are a particularly versatile and basic an element of programming in Ruby. During this tutorial, you created arrays and accessed individual components. You furthermore may more, removed, changed components in an array. Finally, you explored 2 ways in which to tell over an array and show its contents, that is employed as a standard technique to show knowledge.

About the author

Venkatesan Prabu

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment