0

I have a statement like this in Ruby:

@mastertest = connection.execute("select code_ver from mastertest")

So now I want to make a copy of this 2-D array, because if I do something like @temp = @mastertest, it makes changes to @mastertest when I make any changes to @temp.

I tried using the following:

@temp = Marshal.load(Marshal.dump(@mastertest))

But this gives me an error saying "no marshal_dump is defined for class Mysql2::Result". So I am assuming that the @mastertest is of some other type than a 2-D array.

Can someone help me how to make a copy of this array?

0

3 Answers 3

1

There are two ways to work here: (dup or clone isn't fully deep copy, only Marshal does).

  1. Use Object#dup or clone. Try @temp = @mastertest.dup. I don't know the format of Mysql2::Result, so this way may fail when it is like a "2-D array", which you have to dup each element in the Enumerable-mixed class. The dup method just calls initialize_copy for that class. If there is anything not POD(plain-old-data) in an array-like object, it will only make a shallow copy for it.

  2. Write your monkey patch for Mysql2::Result with two methods: marshal_dump and marshal_load. This will make it respond to Marshal.dump. See the doc about Marshal here.

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

Comments

0

Try

@temp = @mastertest.clone

Now changes to @temp will not affect the @mastertest

1 Comment

This will not work for something like 2-D array. For example, a = [[1,2]] b = a.dup a[0] << 3 puts b.
0

I managed to solve this by using the following:

@new_array = Array.new
@mastertest.each { |r| @new_array.push(r[0]) }

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.