Dynamically Generate Multi-Dimensional Array in Ruby

Posted by user335729 on Stack Overflow See other posts from Stack Overflow or by user335729
Published on 2010-05-08T21:28:42Z Indexed on 2010/05/08 21:38 UTC
Read the original article Hit count: 140

Hi, I'm trying to build a multidimensional array dynamically. What I want is basically this (written out for simplicity):

b = 0

test = [[]]

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

This gives me the error: NoMethodError: undefined method `<<' for nil:NilClass. I can make it work by setting up the array like

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

and it works fine, but in my actual usage, I won't know how many arrays will be needed beforehand. Is there a better way to do this? Thanks

© Stack Overflow or respective owner

Related posts about ruby

Related posts about arrays