我在Ruby中有这样一条语句:
@mastertest = connection.execute("select code_ver from mastertest")所以现在我想复制这个二维数组,因为如果我执行类似@temp = @mastertest的操作,当我对@mastertest进行任何更改时,它就会对@temp进行更改。
我尝试使用以下代码:
@temp = Marshal.load(Marshal.dump(@mastertest))但这给了我一个错误,即"no marshal_dump is defined for class Mysql2::Result"。因此,我假设@mastertest不是二维数组,而是其他类型。
有人能帮我制作这个数组的副本吗?
发布于 2012-10-20 02:16:05
我设法解决了这个问题,使用了以下方法:
@new_array = Array.new
@mastertest.each { |r| @new_array.push(r[0]) }发布于 2012-10-17 17:42:31
这里有两种工作方式:(dup或clone不是完全的深度拷贝,只有Marshal才是)。
@temp = @mastertest.dup。我不知道Mysql2::Result的格式,所以当它像一个"2-D数组“时,这种方法可能会失败,你必须对Enumerable-mixed类中的每个元素进行重复操作。dup方法只为该类调用initialize_copy。如果在一个类似数组的对象中有任何不是POD(普通旧数据)的东西,它只会为它做一个浅拷贝。Mysql2::Result编写猴子补丁:marshal_dump和marshal_load。这将使其响应Marshal.dump。请参阅文档about Marshal here.发布于 2012-10-17 17:50:50
试一试
@temp = @mastertest.clone现在,对@temp的更改将不会影响@mastertest测试
https://stackoverflow.com/questions/12931025
复制相似问题