2

I would like to create a new array by inserting a new element to an existing array. But I do not want to mutate the existing array. I want:

A = [1, 2, 3]

to remains as is, while creating:

B = [1, 2, 3, 4]

Any suggestions?

This code:

B = A << 4

results in:

B = [1, 2, 3, 4]
A = [1, 2, 3, 4]

2 Answers 2

6

Do

B = A + [4]

or

B = [*A, 4]

or

B = A.dup << 4
Sign up to request clarification or add additional context in comments.

7 Comments

For completeness - this still will not fully decouple those arrays, as both of the arrays are still pointing to the same objects. It is absolutely fine for fixnums, but might bring some pain with mutable objects.
@BroiSatse I don't get your comment. B is a newly created one, and A indeed points to the same object as before. If you are mentioning the necessity to deep duplicate, then that is a valid note.
As I said it is only for completeness. Your answer is 100% correct, however OP might need to know about those potential issues, as they are pretty common.
Yes, even though A and B are different arrays, they include exactly same objects, so if you modify the first element of A, it will modify B (well, will not modify B, but an object stored within B). This is so a common issue I thought it is worth mentioning it here.
To fully dump an array, you can use marshalling, like B = Marshal.load(Marshal.dump A) (why are you using constants here btw?) Another way, slightly cleaner and more obvious is to implement deep_dup methods. You can steal it from ActiveSupport: api.rubyonrails.org/files/activesupport/lib/active_support/…
|
0

when you assign one array it just copies the reference and both of them point to the same reference. so a change in one is reflected when you print either of them.

orig_array = [1,2,3,4]<br>
another_array = orig_array

puts orig_array.unshift(0).inspect
puts another_array.inspect

Output:

[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]

To avoid this you can use Marshal to copy from original array without impacting the object to which it is copied. Any changes in the original array will not change the object to which it is copied.

orig_array = [1,2,3,4]<br>
another_array = Marshal.load(Marshal.dump(orig_array))

puts orig_array.unshift(0).inspect
puts another_array.inspect

Output:

[0, 1, 2, 3, 4]
[1, 2, 3, 4]

I have already pasted this answer in another thread. Change value of a cloned object

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.