Search⌘ K
AI Features

Exercise 5: Retrieve and Recombine Elements of an Array

Explore how to retrieve specific elements from an array and recombine them into a new array in Ruby. This lesson helps you understand basic array indexing and introduces the concept of the select method, preparing you for more advanced Ruby programming techniques.

We'll cover the following...

Problem statement

You’re given the following array:

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Make a new array with the following output:

result = [2, 4, 6]

Try it yourself

Ruby
def combine_elements(input_array)
result = []
# Start your code here
return result
end

The given solution is inelegant, but it at least shows how we can use the value returned from an array lookup and immediately create a new array.

A more elegant solution to this uses the select method. However, we’ll need to learn more about methods and blocks before we’ll be able to fully understand it!