Array methods every Ruby developer should know

This article will discuss Ruby array methods every Ruby developer should know. These methods are each, map, select, reject, select!, reject!, compact and include?. This article will also discuss the comparison of these methods where applicable.

Let’s start with a comparison of map vs each.

each vs map

In Ruby, Array.each and Array.map are the methods that are used to iterate over arrays. One common difference between these two is that each performs an operation that is defined in the block over its elements but does not change the original array. Also, it returns the original array.

1
2
3
4
5
6
7
8
9
10
11
arr = [1,2,3,4,5]
arr.each {|a| puts a * 2}
2
4
6
8
10
=> [1, 2, 3, 4, 5] 

arr
=> [1, 2, 3, 4, 5] 

Whereas map performs an operation and returns a new array on which the operation defined by the block is applied, but it leaves the original array unchanged.

1
2
3
4
5
arr = [1,2,3,4,5]
arr.map {|a| a * 2}
=> [2, 4, 6, 8, 10] 
arr
=> [1, 2, 3, 4, 5] 

map! can also be used to make changes to the original array.

1
2
3
4
5
arr = [1,2,3,4,5]
arr.map {|a| a * 2}
=> [2, 4, 6, 8, 10] 
arr
=> [2, 4, 6, 8, 10] 

There are different methods for selecting elements from an array based on any criteria given in the block. The selection can be divided into two types, Destructive Selection or Non-Destructive Selection. Destructive Selection makes the changes in the original array, whereas Non-Destructive Selection leaves the original array unchanged. First, let’s go through Non-Destructive Selection.

select vs reject

1
2
3
4
5
6
7
8
9
10
11
arr = ['a', 'b', 'c', 'd']
arr.select {|a| a > 'a'}
=> ["b", "c", "d"] 
arr
=> ["a", "b", "c", "d"]

arr = ['a', 'b', 'c', 'd']
arr.reject {|a| a > 'a'}
=> ["a"] 
arr
=> ["a", "b", "c", "d"] 

Now let’s look at Destructive Selection methods.

select! vs reject!

1
2
3
4
5
6
7
8
9
10
11
arr = ['a', 'b', 'c', 'd']
arr.select! {|a| a > 'a'}
=> ["b", "c", "d"] 
arr
=> ["b", "c", "d"] 

arr = ['a', 'b', 'c', 'd']
arr.reject! {|a| a > 'a'}
=> ["a"] 
arr
=> ["a"] 

Another important Ruby array method is compact. Assume having a large array that can also contain nil values. They can be deleted from the array using the compact method.

1
2
3
4
5
arr = [1, 2, 'a', 'b', nil, 0, '', 10]
arr.compact
=> [1, 2, "a", "b", 0, "", 10] 
arr
=> [1, 2, "a", "b", nil, 0, "", 10] 

There is also a Destructive version of compact, i.e. compact!.

1
2
3
4
5
arr = [1, 2, 'a', 'b', nil, 0, '', 10]
arr.compact!
=> [1, 2, "a", "b", 0, "", 10] 
arr
=> [1, 2, "a", "b", 0, "", 10] 

Last but not least, we have the Array.include? method. It returns ‘true’ or ‘false’ if a particular element is present in an array.

1
2
3
4
5
arr = ['apple', 'banana', 'orange']
arr.include?('banana')
=> true 
arr.include?('mango')
=> false 

These are all methods that will be useful for any Ruby developer to have in their toolkit.