Ruby array is a strange thing (infinite array)

When I write the following code:

x= [1,2,3]
x << x
puts x
puts x[3]
puts x[3][3][3][3][3][3][3][3][3][3]

I get this output:

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

Should I get only [1,2,3, [1,2,3]] and what will be the explanation?

+5
source share
2 answers

There is nothing strange about this. The fourth element of the array is the array itself, so when you request the fourth element, you get an array, and when you request the fourth element of the fourth element, you get an array, and when you request the fourth element of the fourth element of the fourth element of the fourth element ... you get an array .

Just like that.

, , , Array#to_s ​​ .

+10

x << x, x , / .

x << x.dup, x x. [1,2,3,[1,2,3]]

+7

All Articles