Here are four Ruby methods you should know when working with arrays:
Each vs. Map
The main difference between map and each is in the return value. Using each will return the original array while map will return a new array.
Example:
Select
The select method will return a new array that contains the elements of the original array for which the given block returns a true value.
Example:
In this example, we selected all the elements in the original array unless the element equaled "a".
Here is another example:
Reject
Reject is the opposite of select. It will return a new array that contains the elements of the original array for which the given block returns a value that is not true.
Example:
In this example, we are returning all the odd numbers in the original array.
There are many more methods that can be called on an array. For more array methods visit https://ruby-doc.org/core-2.4.1/Array.html
Thanks!
Top comments (0)