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, [...]]
Written by Tony612
Related protips
2 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Related Tags
#ruby
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#