0

I have array, named a and define it with [1, 2, 3].

Next, I pushed it to itself:

a = [1, 2, 3]
a << a

and the result I get is:

#=> [1, 2, 3, [...]]

When I want to get the last element of array using a.last I get:

a.last
#=> [1, 2, 3, [...]]
#even 
a.last.last.last
#=> [1, 2, 3, [...]]

What is going on, when we would push array to itself?

Yes, I understand that this should create a recursive array, but what can we do with it?

5
  • 5
    "what we can do with it" – make coffee if you type enough .last and make the CPU produce enough heat…? I'm not sure what kind of answer you're expecting here… Commented Oct 31, 2016 at 13:40
  • I didn't know ruby handles it this well :) Commented Oct 31, 2016 at 13:43
  • 1
    @deceze I mean, maybe someone know how to use recursive array in real work examples Commented Oct 31, 2016 at 13:43
  • 2
    I'm sure there are real world use cases for this, and you will know them when you encounter them. Coming up with random examples is not really a productive question for SO. Commented Oct 31, 2016 at 13:44
  • They're pretty useful in Mathematics, as couter-examples. Your recursive array is basicaly infinitely long. If you make one step towards infinity, you basically didn't move at all ;) Commented Oct 31, 2016 at 13:45

2 Answers 2

2

In Ruby variables, array elements etc. are object references. So when you do a = [1, 2, 3], there will be an array somewhere in memory and the a variable is a reference to that memory. Now when you do a << a, a[4] will also be a reference to that object. So in effect a now contains a reference to itself.

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

Comments

1
a = [1, 2, 3]
a << a.dup
a.last
=> [1, 2, 3]  
a.last.last
=> 3 

Maybe this is what you wanted. This just insert an array [1, 2, 3] as the last item of the a array. In the way you did you put a reference at the end of the a array and this becomes recursive.

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.