Last Updated: May 30, 2022
·
760
· tony612

The result of n << n

The problem is like this:
n = [1, 2] a = n << n p a => [1, 2, [...]] a[2] => [1, 2, [...]]
That is to say, a is a infinite recursive Array.

My explaination is:
When the right n append(<<) the left n, the left n changed to [1, 2, [1, 2]]. But at this moment, the right n, which is the same with the other(they have the same object_id), became '[1, 2, [1, 2]]', too.
......
And repeat the process, a = [1, 2, [...]]

2 Responses
Add your response

Array in ruby contains "pointers" to other objects. You're just adding pointer to array itself. Interesting though.

over 1 year ago ·

@sheerun Interesting indeed. So basically when I do n = []; n << n, n becomes a self-referencing Array, right?

over 1 year ago ·