This code is valid in Ruby
a = [5,10,15]
[5,10,15]
a.push a
[5,10,15,[...]]
Resulting in the fourth array slot pointing to the array itself, (seemingly) infinitely. Why does Ruby allow this and does the functionality offer any practical applications?
Since in Ruby everything is an object, variables just point to the objects (more strictly speaking, memory locations). An array is a collection of such a pointers, which means it can store a pointer to itself. It is not an extra feature added in Ruby, it would be actually an extra feature not to allow it.
As for application, check out "What are recursive arrays good for?" (directed graph representation).
Note however, that such an array is not infinite:
a = []
a << a
a.length = 1
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