在Ruby中动态生成多维数组

MWe*_*ean 5 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"]
Run Code Online (Sandbox Code Playgroud)

这给了我错误:NoMethodError:nil的未定义方法`<<':NilClass.我可以通过设置数组来使其工作

test = [[], [], []]
Run Code Online (Sandbox Code Playgroud)

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

Jer*_*ten 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"]]
Run Code Online (Sandbox Code Playgroud)


Jak*_*mpl 5

不要使用该<<方法,=改为使用:

test[b] = ["a", "b", "c"]
b += 1
test[b] = ["d", "e", "f"]
b += 1
test[b] = ["g", "h", "i"]
Run Code Online (Sandbox Code Playgroud)

或者更好的是:

test << ["a", "b", "c"]
test << ["d", "e", "f"]
test << ["g", "h", "i"]
Run Code Online (Sandbox Code Playgroud)