Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Ruby allow me to push an array on itself? [duplicate]

Tags:

arrays

ruby

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?

like image 601
Aaron Marks Avatar asked May 24 '26 09:05

Aaron Marks


1 Answers

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
like image 192
BroiSatse Avatar answered May 27 '26 05:05

BroiSatse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!