1

Somebody tell me what's going on here:

a = [0,1,2]
a.each {|x| a[x] = a}

The result is [[...], [...], [...]]. And if I evaluate a[0] I get [[...], [...], [...]]. And if I evaluate a[0][0] I get [[...], [...], [...]] ad infinitum.

Have I created an array of infinite dimensionality? How/Why should this possibly work?

3
  • Why not? at position a[x] you find a, on which you can call a[x] again, etc., etc. Dimensionality always has also to do with orthogonality. This premise isn't given here. Commented Jan 17, 2011 at 19:38
  • 1
    Note that this has nothing to do with blocks. a = []; a[0] = a; a[1] = a; a[2] = a will have exactly the same result. Commented Jan 17, 2011 at 19:49
  • Using blocks you can actually (not quite) create an infinite dimensional array blk = proc { |i| Array.new(10, &blk) }; a = Array.new(10, &blk). This causes a SystemStackError though as Ruby can't handle infinite recursion. Commented Jan 17, 2011 at 19:57

2 Answers 2

3

Basically you've modified every element in a to reference the list itself. The list is recursively referencing itself:

a[0] # => a
a[0][0] # => a[0], which is a
a[0][0][0] # => a[0][0], which is a[0], which is a
...

(# => is a Rubyism for "this line evaluates to")

Depending on how you look at it it is not infinite. It's more or less just like a piece of paper with the words "please turn over" written on both sides.

The reason that Ruby prints [...] is that it is clever enough to discover that the list is recursive, and avoids going into an infinite loop.

By the way, your usage of each is a bit non-idiomatic. each returns the list, and you usually don't assign this return value to a variable (since you already have a variable referencing it, a in this case). In other words, your code assigns [0,1,2] to a, then loops over a (setting each element to a), then assigns a to a.

Sign up to request clarification or add additional context in comments.

3 Comments

Ah... I see. I don't think I've ever played with a language where you could do this.
@John: You can do this in almost any language. Including C, C++ (using explicit pointers or references), java, C#, python and many others.
Ah... I see. And I'm starting to feel kinda dumb. In retrospect, this all probably should have been obvious.
1

I think it's a self-referential data structure. The a[x]=a puts a's pointer in a[x].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.