Familiarize yourself with Array in Ruby

Tram Ho

This article is in my basic Ruby series. Basic, so only very basic knowledge for new friends to Ruby. This article I would like to mention to you about arrays.

Array is probably the most common data structure you will use in Ruby. They allow you to group data together into a list of elements.

Array elements don’t need to be the same type, they can be anything, even other arrays if you want.

Array in Ruby inherits from Object and it includes the Enumerable module (you can read more about Enumerable through your other posts here )

Initialize an array

Here is an example of an array:

You can also initialize an array with the new method. It may have the original size and default object. If you do not specify any arguments, it will create an empty array.

The second argument in Array.new is used to fill the array with reference to that object.

If you want to initialize the array with separate objects, you need to pass it a block.

And the last way you can initialize the array is to use the Kernel.Array() method (or simply Array() ) and pass the object in.

As usual, we often use the declaration as on the first example of the article 😃

Accessing elements in arrays

Unlike key access hashes , we access the element in the array through its position. In arrays, the elements are numbered from 0.

You can use the [] , slice , at methods with the position of an element in an array to access that element.

Negative indicators will be accessed from the bottom. In addition, there is a first method to access the first element, last to access the last element of the array.

Another way is to use fetch method with the argument is the position of the element in the array. Using fetch different ways in the above it will return an error that no element array with the order passed, the other method returns nil .

How to retrieve multiple elements

The above only mentions that only one element can be removed at a time. See how to retrieve multiple elements in the array.

You can use how to specify the start and end index, or the range of the index, for example:

The take method with arguments is used to retrieve the first number of elements. If you want to get the first 3 elements, you just need to call take(3) as follows:

Similarly, you can retrieve a final number of array elements by removing the first few elements, using the drop method.

Check if the value exists

The first and most obvious is to see if an element exists at a specific index. And you already know how to do that.

As seen above, doing this with an array with nil element will cause a bit of misunderstanding.

If you want to check if the array contains an element with a specific value, you can use the any? method any? or include? as follows.

When you want to return the result that the value is checking or the index of that element, for example, to find the element with the first letter is d , we can use the find or find_index method as follows:

Notice here that the find and find_index method will return the first element in the array of conditions.

Calculate the sum of the array of numbers

You have 2 ways to do this and which method to choose depends on the context. The simplest way is with sum .

Note that if the element is a string, sum still work when you pass the argument to it as follows:

The other way is to use inject or reduce (these two methods just define different names, and the implementation is the same, some versions of Ruby will recommend using reduce ).

Randomly retrieve element

The simplest is that you use the sample method to randomly retrieve 1 or more elements in the array, as in the following example:

Delete the duplicate elements

Ruby provides us with the uniq method – which returns the new array after removing the duplicates.

Arrange the array

We will use sort method – default sort in ascending order. Or you can pass a block to the sort method to show how we compare the two elements in the array to rearrange the array. If you want to sort your descending array, you can do the following:

Or you can combine regular and reverse sort as follows:

Also, when dealing with more complex data, you can use the sort_by method to get a better effect.

Delete empty element in array

Assuming you are trying to retrieve a child array from an initial array after you have removed the empty element, you can pass a block to the inject method as follows:

And can be combined with strip for better results:

Bonus for the compact method – remove all nil elements in the array.

Putting the pieces together

The first way is simply to use the + operator

It can be seen that element 2 is repeated, and if this is not desirable then we can switch to using | .

In both ways above, we will create a new array, if you want to change immediately on the existing array, you can do the following:

Combine array into string

You can use join (with arguments if needed) to join the elements in the array into a string.

If you want to go back from string to array, you can use chars or split .

Loop through array

There are many methods that support you to loop through the elements in the array.

  • each : used when you are not interested in the index
  • each_with_index : used to retrieve the value – index pair
  • each_index : only get index
  • map : when you want to create a new array from an initial array
  • select : when you want to retrieve a conditional sub array
  • inject : is used to render a single result from array elements


Hope the article will be useful to you.


Chia sẻ bài viết ngay

Nguồn bài viết : Viblo