What's the return value of the following Ruby 3 code?

array = [1, [2]]
array[1] << array

array.flatten # => ???

The correct answer is

[1, 2]

[1, [2, 1, 2]]

[1, [2, [1, [2]]]]

It raises ArgumentErrorr

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

Flattening an array that contains itself as an element can lead to an infinite loop.

This happens because the flatten method attempts to recursively flatten all nested arrays, and a self-referencing array creates an endless recursion.

Example of Recursive Array

Consider the following example where an array contains itself:

array = [1, [2]]
array[1] << array

In this example:

  • array initially contains two elements: the integer 1 and another array [2].
  • We then modify the second element (which is [2]) to include the original array itself, resulting in a recursive structure.

The resulting array looks like this:

[1, [2, [...]]]

Here, [...] represents the recursive reference to the original array.

Flattening the Recursive Array

Attempting to flatten this recursively defined array with the flatten method will throw an error:

array.flatten
# => `flatten': tried to flatten recursive array (ArgumentError)

The flatten method continuously tries to flatten the nested arrays, but since one of the nested arrays is the array itself, it will never terminate.

Instead, Ruby raises an ArgumentError with the message tried to flatten recursive array to indicate the issue.

Voilà!

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©