Coding Ruby

Work with Arrays in Ruby

ruby-logo

Work with Arrays in Ruby

Introduction

  • 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:
emails.rb
email1 = "ceo@example.com"
email2 = "admin@example.com"
email3 = "support@example.com"
email4 = "sales@example.com"
  • 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:
emails.js
emails = [
  "ceo@example.com",
  "admin@example.com",
  "support@example.com",
  "sales@example.com"
]
  • 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];

Output

ceo@example.com

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

Output

["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:
mixed_data.rb
record = [
    "Sammy",
    null,
    7,
    [
        "another",
        "array",
    ]
]

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.rb
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  C Programming-Write a program to print all permutations of a given string
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.

sharks.length

Output

3

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")

Output

2

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")

Output

nil

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

print sharks[-1]

Output

"Tiger"

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

puts sharks.first
puts sharks.last

Output

"Hammerhead"
"Tiger"

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

sharks[10]

Output

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 = [
    [
        "salmon",
        "halibut",
    ],
    [
        "coral",
        "reef",
    ]
]

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];

Output

coral

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

Output

["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;

Output

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

Access extra array element which returns the nil value

sharks[4]

Output

nil

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:

sharks.push("thresher")
print sharks

Output

["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
array:

sharks << "Bullhead"

Output

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

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

sharks.unshift("Angel")
print sharks

Output

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

let’s cross-check removing them.

READ  C Program for Tower of Hanoi

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)

Output

4

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

sharks.delete_at(4)
print sharks

Output

["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:

sharks.delete("Whale")
print sharks;

Output

["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.

sharks.pop
print sharks;

Output

["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.

sharks.shift
print sharks

Output

["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.rb
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}"

Output

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;

Output

["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  Use Array Methods in Ruby

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 for..in syntax, that appears like this:

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

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 for..in 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 for..in, however, incorporates a totally different syntax:

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

Output

Hammerhead
Great White
Tiger
Whale

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:

each.rb
...
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:

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

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:

Output

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.

Conclusion

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