在Ruby中动态生成多维数组

时间:2010-05-08 21:28:42

标签: ruby arrays multidimensional-array

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

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`&lt;&lt;'为零:NilClass。我可以通过设置像

这样的数组来使其工作
test = [[], [], []]

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

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分: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"]

答案 2 :(得分:0)

如果您知道要创建的数组的大小,这是一个简单的示例   @ OneDArray = [1,2,3,4,5,6,7,8,9]         p_size=@OneDArray.size         c_loop = P_SIZE / 3         把“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]]