【问题标题】:Dynamically Generate Multi-Dimensional Array in Ruby在 Ruby 中动态生成多维数组
【发布时间】:2011-02-17 06:01:08
【问题描述】:

我正在尝试动态构建一个多维数组。我想要的基本上是这个(为简单起见写出来):

b = 0

test = [[]]

test[b] << ["a", "b", "c"]
b += 1
test[b] << ["d", "e", "f"]
b += 1
test[b] << ["g", "h", "i"]

这给了我错误:NoMethodError: undefined method `

test = [[], [], []]

它工作正常,但在我的实际使用中,我不会事先知道需要多少个数组。有一个更好的方法吗?谢谢

【问题讨论】:

    标签: ruby arrays multidimensional-array


    【解决方案1】:

    如果您知道要创建的数组的大小,这是一个简单的示例。
    @OneDArray=[1,2,3,4,5,6,7,8,9] p_size=@OneDArray.size c_loop=p_size/3 puts "c_loop is #{c_loop}" 左=p_size-c_loop*3

    @TwoDArray=[[],[],[]]
    k=0
    for j in 0..c_loop-1
           puts "k is  #{k} "
            for i in 0..2
             @TwoDArray[j][i]=@OneDArray[k]
          k+=1
        end
     end
    

    结果将是 @TwoDArray= [[1,2,3].[3,4,5],[6,7,8]]

    【讨论】:

      【解决方案2】:

      不需要像您正在使用的索引变量。只需将每个数组附加到您的 test 数组即可:

      irb> test = []
        => []
      irb> test << ["a", "b", "c"]
        => [["a", "b", "c"]]
      irb> test << ["d", "e", "f"]
        => [["a", "b", "c"], ["d", "e", "f"]]
      irb> test << ["g", "h", "i"]
        => [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
      irb> test
        => [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
      

      【讨论】:

        【解决方案3】:

        不要使用&lt;&lt; 方法,而是使用=

        test[b] = ["a", "b", "c"]
        b += 1
        test[b] = ["d", "e", "f"]
        b += 1
        test[b] = ["g", "h", "i"]
        

        或者更好:

        test << ["a", "b", "c"]
        test << ["d", "e", "f"]
        test << ["g", "h", "i"]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-11-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-14
          相关资源
          最近更新 更多