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?
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.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With