在Ruby中动态生成多维数组

5
我正在尝试动态构建多维数组。我想要的基本上是这样的(为了简单起见写出来):
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 `<<' for nil:NilClass。如果我像这样设置数组,它可以正常工作:
test = [[], [], []]

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

3个回答

7
无需使用像您正在使用的索引变量。只需将每个数组附加到您的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"]]

5

不要使用<<方法,改用=代替:

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"]

0

如果您知道要创建的数组的大小,这里有一个简单的示例。
@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}" left=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]]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接