[Ruby] Array handling methods in Ruby

Tram Ho

Arrays are one of the basic constructs of programming. It appears everywhere and almost always when manipulating data we always need arrays to process. Therefore, mastering and successful manipulating array operations is an extremely important and necessary, especially for beginners like me.
Here I would like to introduce some array processing techniques that are considered quite popular and you need to understand it thoroughly, these are the first steps to becoming a true Ruby dev.


Browse through the elements in the array and manipulate them:

Nothing much to say to each . The only small note is that each will luôn luôn trả về mảng gốc matter how you transform.

Map / Collect

Map and Collect are alias_method of each other so when using any guy, I see that most people use map more, maybe it's more concise than collect ?
Nothing is easier to understand than going straight to the example:

If you want to change the original array always use map! .
When you first started with ruby, I bet most of you use each as the main right? Try the following simple code

… you can simplify by using the map only takes 1 line only:

Or even better and faster ( better and faster ):

Pinch the skirt, map (hoặc collect) will return the new array has been processed, use the map make your code cleaner.

Select and Detect

.select allows you to "search" for elements in the array. You need to include .select a conditional statement that returns true or false since it will help you know whether or not the elements you want to search in the array are.
.detect is similar to .select but instead of removing all the elements that satisfy the screen, .detect only takes the first guy (only 1 guy)
Let's try, for example, retrieving even parts in an array ( .select we don't know .select ):

Using .map to get even guys but in return you give birth to nil guys, so I need to use the compact function to get rid of nil guys, now we have what we need but handle it seems a bit cumbersome.

Ruby gave your teeth to you already! Only a simple line of code, easy to understand then what are you waiting for: v
Bonus: better and faster

Note: So .select retrieves all the .select who qualify. .detect only retrieve the first guy that meets the conditions.
By the way, I would like to introduce the .compact function to help remove nil elements in a memory array


.reject the complete opposite of .select . Instead of taking out what we need (ie .select ), we will remove the elements that satisfy the set.

Since the above example can see, with .select will retrieve the .select from <3 (ie [1, 2]), then .reject is to remove the <3 elements (ie [3, 4, 5] ).
.select , when you want to get what you need, use .select , when you want to remove unwanted parts, use .reject .


Reduce has a more complex structure than other array processing methods, but in return it is often used quite simply in ruby, mainly for the calculation of elements in the array and then returned. The results have just finished.
Try with a simple example: Calculate the sum of the elements in an array.

We can also manipulate the String array in the same way:

As a final note about .reduce , sometimes the data you manipulate is old data (not empty or 0), you need to pass an argument to initialize the original value:


.join is really useful when working with arrays, especially in relation to String

.join very similar to .reduce except that it has a "super clean" owl. .join needs to pass an argument – which will connect the elements together into a string.

Why not combine methods together

Now we can still use the knowledge above to handle it at the same time.
We have an array of 10 working days, each day corresponding to 1 task and the estimated time of each task is random. Now I want to retrieve the total time of all tasks with the condition that ignoring tasks with estimates greater than 30 minutes as well as tasks with estimates less than 5 minutes:

The above example may not seem very relevant, but the main purpose here is that we know how to combine methods together.
P / S: What ? : may be strange for some of you don't know, it's the trinity operator is an abbreviation of if-else, in this case due to the simple problem, so I use it, but for the case complex logic, then I advise you not to use.



I have an array of integers, what do I want to get out of any number?

Use .sample to make your code more .sample .


This function helps you clone data from a given array, you just need to specify the starting index value and the ending index you want to clone:


Help you check if your input is in a given data array


Help you delete duplicates in array quickly


I hope this is helpful for some of you, not really all but enough for you to work the array smoothly. Many thanks for reading my article ?



Share the news now

Source : Viblo