0

I'm totally new to Ruby. I came across something that I'm unable to explain.

Here is my code:

arr1 = []
arr2 = [0]

5.times{
  arr2[0] += 1
  arr1 << arr2
  }
puts "result = #{arr1}"

I was expecting the following result:

result = [[1],[2],[3],[4],[5]]

However, this is the result I'm getting:

result = [[5],[5],[5],[5],[5]]

Can someone explain to me why this happens? how I can fix it?

Many Thanks,

1
  • Try arr1 += arr2. What I think is happening is you are adding the same arr2 five times, so it gets updated even when it's in arr1 Commented Apr 14, 2015 at 2:38

2 Answers 2

2

So, you're not just adding the value of arr1 to arr2. You're actually adding arr1 itself to arr2. Then you're adding arr1 to arr2 again, now it's got the same array in there twice.

You may want to add a copy of arr1 to arr2 instead.

arr1 << arr2.dup
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I realize now what I'm doing wrong. Thanks for your answer
0

The problem I see is that your changing the value of a mutable structure.

You keep mutating arr2 and inserting the same instance into arr1

If you trace through the execution

arr2[0] +=1  # arr1 = [],    arr2 = [1]
arr1 << arr2 # arr1 = [[1]], arr2 = [1]

arr2[0] +=1  # arr1 = [[2]],     arr2 = [2]
arr1 << arr2 # arr1 = [[2],[2]], arr2 = [2]

arr2[0] +=1  # arr1 = [[3],[3]],     arr2 = [3]
arr1 << arr2 # arr1 = [[3],[3],[3]], arr2 = [3]

...

You can verify that it's the same instance you are inserting by doing this:

arr1.map(&:hash).uniq

1 Comment

Interesting, I didn't go through the concept of mutable/immutable objects before. Now that I've read it, many things are making sense

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.