DEV Community

Josh Phelps
Josh Phelps

Posted on

Ruby Methods: Each, Map, Select, and Reject Explained

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:

Alt Text

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:

Alt Text

In this example, we selected all the elements in the original array unless the element equaled "a".

Here is another example:

Alt Text

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:

Alt Text

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)