Ruby Array Methods That Will Blow Your Mind, Pt. 4: Fusions

RMAG news

This is the second to the last part of this series where we consider some more interesting methods to combine array of arrays into one single array.

zip

The zip method in Ruby arrays is used to combine corresponding elements from two arrays into an array of arrays.(Whew 🤯 so many arrays in there and yet more to come). It takes one or more arrays as arguments and returns a new array of arrays. Each sub-array contains the elements at the same index from each of the input arrays. If the arrays are of different lengths, nil values are used to fill in the gaps.

array1 = [1, 2, 3]
array2 = [‘a’, ‘b’, ‘c’]
result = array1.zip(array2)

# Output: [[1, ‘a’], [2, ‘b’], [3, ‘c’]]

In this example, zip is called on array1 with array2 as an argument. The method combines the elements of array1 and array2 that have the same index into a new array of arrays.

flatten

Well you guessed it, the flatten method used to flatten a nested array. This method transforms the nested array into a one-dimensional array. It’s important to note that the ‘flatten’ method doesn’t modify the original array unless it’s called as ‘flatten!’. Another important bit to note is that flatten doesn’t take a block which is one very vital distinguising factor from flat_map described below.

nested_array = [[1, 2, [3, 4]], [5, 6], 7]
flattened_array = nested_array.flatten
puts flattened_array
# Output: [1, 2, 3, 4, 5, 6, 7]

In the above code, the ‘flatten’ method is called on the ‘nested_array’. The result is a new array ‘flattened_array’ where all elements are in a single, un-nested level.

flat_map

The flat_map method is literally a combination of the normal map and flatten methods. It is used to transform each element using a block and then flatten the result into a single array. This method is particularly useful when you want to map over an array, and the block you pass returns an array for each element. The flat_map method will flatten all of these into a single array.

arrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_mapped = arrays.flat_map { |array| array }

# Output: flat_mapped will be [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Just returning the elements behave like the normal `flatten`

arrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_mapped = arrays.flat_map { |array| array * 2 }

# Output: flat_mapped will be [1, 2, 3, 1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9, 7, 8, 9]

In the above example, flat_map is called on an array of arrays. The block passed to flat_map simply returns each sub-array as it is in the first example while in the second, it doubles the array then flattens it into a single array.

If you know other interesting methods don’t be shy to drop it in the comments as we prepare to go through the last bit in the series of interesting Ruby Array methods.

Leave a Reply

Your email address will not be published. Required fields are marked *