Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby array 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, [...]]

Shouldn't I get only [1,2,3,[1,2,3]] and what would be the explanation?

like image 727
Dragos Avatar asked Sep 07 '11 15:09

Dragos


2 Answers

There's nothing strange about this. The fourth element of the array is the array itself, so when you ask for the fourth element, you get the array, and when you ask for the fourth element of the fourth element, you get the array, and when you ask for the fourth element of the fourth element of the fourth element of the fourth element ... you get the array.

Simple as that.

The only slightly unusual thing is that Array#to_s detects such recursion and instead of going into an infinite loop, returns an ellipsis.

like image 74
Jörg W Mittag Avatar answered Oct 13 '22 19:10

Jörg W Mittag


When you write x << x you are appending to x with a reference to itself, creating a recursive/infinite array.

Compare this with x << x.dup which appends a copy of x onto x. This is equal to [1,2,3,[1,2,3]]

like image 38
mikej Avatar answered Oct 13 '22 18:10

mikej