Welcome! In this lesson, we’re diving into an engaging task involving arrays: pairing up 'opposite' elements.
This is a perfect opportunity to enhance your skills in accessing and manipulating elements in Ruby arrays. Are you ready to jump in? Let’s get started!
Our task is to pair up 'opposite' elements in a given array of integers. For an array of n
elements, the first and last elements are considered 'opposite', the second and second-to-last are 'opposite', and so forth. If the array length is odd, the middle element is paired with itself.
You are provided with an array of integers, with the size n
ranging from 1 to 100, inclusive. The goal is to return an array of arrays, where each sub-array consists of a pair of an element and its 'opposite' element.
For instance, given numbers = [1, 2, 3, 4, 5, 6, 7]
, the output should be pair_opposite_elements(numbers) = [[1, 7], [2, 6], [3, 5], [4, 4], [5, 3], [6, 2], [7, 1]]
.
Before writing the code, let’s review how to access elements in Ruby arrays.
In Ruby, the i
-th element of an array numbers
can be accessed using numbers[i]
, where indexing starts at . Therefore:
