zoopz
zoopz

Reputation: 1169

How do I ensure an array operation is done by value rather than reference in ruby?

I'm new to ruby and was wondering how I'd go about this

For example:

a = [1,2,3,4]
b = []

b.push(a)
a.pop
a.pop

print b
# => [[1,2]]

I was expecting b to remain [[1,2,3,4]]

a seems to be pushed into b by reference, rather than value. I'd like b to stay as it is regardless of what I do to a in the future; how do I go about doing this in Ruby?

Upvotes: 2

Views: 72

Answers (2)

Wand Maker
Wand Maker

Reputation: 18762

You could use splat operator and push elements of a into b instead of whole array a.

b.push(*a)
#=> [1, 2, 3, 4]

If you wanted to push an array, then, use

b.push([*a])
#=> [[1, 2, 3, 4]]

Upvotes: 1

banana
banana

Reputation: 613

a is an array reference, so to push its value into b, you'll need to copy it:

b.push(a.dup)

This is similar to using strdup in C, where strings are pointers.

Upvotes: 3

Related Questions