Methods of arrays in Ruby

Tram Ho

Array – An array representing the list of data in your program. When you have data in an array, you can sort, delete duplicates, reverse the order, extract elements, or search for specific data in the array. You can also convert an array to a string, convert an array into another array, and turn an array into a single value. In this tutorial, you will explore some of the most common methods Ruby provides to work with arrays.

1. Access to an element

If you’ve followed the How To Work with Arrays in Ruby tutorial, you already know how to access an element in an array using its index, starting with 0, for example:

  • first & last : You can also call the terminal element by the first & last method:

  • fetch : when you access an element that does not exist, you will get the value nil. But if you want to return an error, you can use the fetch method:

If you want to create a default for an element that doesn’t exist, you can do the following:

2. Retrieve multiple elements

Many times you want to retrieve a subset of elements from an array instead of just one. If you specify a starting index, then the number of elements you want, you will get a new array containing those values. For example:

  • slice : You can also use slice to do the same thing:

The slice method also returns a new array, without changing the original array. However, if you want to change, you can use the slide! method slide!

  • take : allows you to get the specified number of elements from the beginning of an array:

3. Randomly retrieve an element from an array

Randomly picking an element from the array can be applied when you are building a random game, …

  • sample :

sample can take a number of arguments as an argument, for example:

4. Search, filter elements

When you want to search for specific elements in an array, you often repeat the conditions until you find them. But Ruby has provided methods to simplify the search process.

  • include? : looks for the presence of an element in the array, returns true / false:

Note, include? Requires an exact condition, for example:

  • find : locate and return the first element that satisfies the condition

find executes the block of code you provide for each element in the array. If the last expression in the block is true , find returns the correct value and stops the loop. If no results are found, then after iterating through all the elements it returns nil .

  • select : is similar to find , except that it returns a new array containing all of the conditions, otherwise it returns an empty array.

  • reject : opposite of select

Both select and reject do not change the original array value, if you want, you can use select! or reject!

  • find_all : alias of select , but does not exist find_all!

5. Arrange the array

  • reverse : reverse the array

reverse does not change the original array, there is a reverse! method reverse! will change the original array

  • sort : sort arrays in ascending order

  • sort_by : sort with given conditions

Both sort and sort_by do not change the original array, if you want you can use sort! or sort_by!

6. Delete the duplicate elements

  • uniq :

  • For two arrays:

7. Data conversion

The map and collect (alias of map) methods can transform the contents of an array, meaning that it can perform an operation on each element in the array.

For example, you can use map to perform arithmetic on each element in an array and create a new array containing new values:

map often used in web applications to convert an array into elements for HTML lists. For example:

map returns a new array, causing the original array to not be modified. Use map! will modify the existing array. And remember that map with alias are collect . You should be consistent and use one or the other in your code.

8. Convert array into string

  • to_s :

  • join : can be combined with the condition to join the elements in the array into a “nice” string

Using map and join is a quick way to convert a range of data. Use map when you want to convert some elements in the array, then use join to join them together. For example:

9. Turn the array into a value

  • each : When you work with a data set, you may find that you need to rearrange the data into a single value, such as a sum. One way you can do this is to use a variable and the each method:

  • reduce : You can use the reduce method to do this. reduce iterates over an array and keeps the total number of operations by performing a binary operation for each element. reduce accepts an initial value for the result, as well as a block with two local values: a reference to the result and a reference to the current element. Inside the block, you specify the logic to calculate the final result. For example:

If you intend to initialize the result to 0, you can omit the argument. For example:

reduce is also that you specify a binary method or a method on an object that accepts another object as its argument, which will execute for each element in the array. reduce then use the result to create a unique value.

Ruby uses some syntax so you can express it as 2 + 2.

reduce allows you to specify a binary method by converting its name into a symbol. That means you can pass : + to reduce to sum the array:

You can use reduce to do more than just adding a list of numbers. You can use it to convert values. Remember that reducing reduces an array to a value. But there is no rule that says the unique value could be another array.

Let’s say we have a list of values ​​we need to convert into integers. but we only want the values ​​to be converted to whole numbers.

We can use reject to remove non-numeric values ​​and then use map to convert the remaining values ​​into integers. But we can do it all in one step with reduce .

Use an empty array as the initial value. Then, in the block, convert the current value to an Integer using the Integer method. If the value can be converted to an integer, Integer will raise an exception, you can catch and assign nil to the value.

Then take the value and put it into array, but only if it doesn’t nil .

Conclude

In this tutorial, you used some methods to work with arrays. You took individual elements, retrieved values ​​by searching in arrays, sorted elements, and you converted data, created new arrays, strings, and totals. You can apply these concepts to solve many common programming problems with Ruby.

Source of translation: https://www.digitalocean.com/community/tutorials/how-to-use-array-methods-in-ruby

Share the news now

Source : Viblo