【问题标题】:Copy a 2-D array to another array in Ruby将二维数组复制到 Ruby 中的另一个数组
【发布时间】:2012-10-17 09:20:01
【问题描述】:

我在 Ruby 中有这样的语句:

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

所以现在我想复制这个二维数组,因为如果我执行@temp = @mastertest 之类的操作,当我对@temp 进行任何更改时,它会更改@mastertest

我尝试使用以下方法:

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

但这给了我一个错误,说"no marshal_dump is defined for class Mysql2::Result"。所以我假设@mastertest 是二维数组以外的其他类型。

谁能帮我复制这个数组?

【问题讨论】:

    标签: ruby-on-rails ruby arrays ruby-on-rails-3 multidimensional-array


    【解决方案1】:

    这里有两种工作方式:(复制或克隆不是完全深度复制,只有 Marshal 可以)。

    1. 使用 Object#dup 或克隆。试试@temp = @mastertest.dup。我不知道 Mysql2::Result 的格式,所以当它像一个“二维数组”时,这种方式可能会失败,你必须复制 Enumerable-mixed 类中的每个元素。 dup 方法只为该类调用 initialize_copy。如果在类似数组的对象中有任何不是 POD(plain-old-data) 的东西,它只会为它制作一个浅拷贝。

    2. 使用两种方法为Mysql2::Result 编写猴子补丁:marshal_dumpmarshal_load。这将使它响应Marshal.dump。请参阅文档about Marshal here

    【讨论】:

      【解决方案2】:

      试试

      @temp = @mastertest.clone
      

      现在对@temp 的更改不会影响@mastertest

      【讨论】:

      • 这不适用于二维数组。例如,a = [[1,2]] b = a.dup a[0] << 3 puts b
      【解决方案3】:

      我设法通过使用以下方法解决了这个问题:

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

      【讨论】:

        猜你喜欢
        • 2021-12-31
        • 2012-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-10
        相关资源
        最近更新 更多