3

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?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Aaron Marks
  • 375
  • 2
  • 7
  • 19
  • 1
    The simplest example I can think of is a garbage collector - you keep a list of references to every object in memory (including that list!) – roippi Apr 28 '14 at 15:35

2 Answers2

3

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
Community
  • 1
  • 1
BroiSatse
  • 44,031
  • 8
  • 61
  • 86
0

Since Ruby is a dynamic language, an array is, in essence, a collection of "any object" so you can push anything you want into it, including other arrays, including (in this case) a reference to itself. It's like an ArrayList<Object> in Java, which can do the same thing (you can add it to itself, but why?)

It might be sometimes useful to have recursive structures, though nothing comes to mind.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
rogerdpack
  • 62,887
  • 36
  • 269
  • 388