Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Generate Multi-Dimensional Array in Ruby

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

like image 676
MWean Avatar asked May 08 '10 21:05

MWean


2 Answers

No need for an index variable like you're using. Just append each array to your test array:

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"]]
like image 51
Paige Ruten Avatar answered Oct 04 '22 21:10

Paige Ruten


Don't use the << method, use = instead:

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

Or better still:

test << ["a", "b", "c"]
test << ["d", "e", "f"]
test << ["g", "h", "i"]
like image 33
Jakub Hampl Avatar answered Oct 04 '22 21:10

Jakub Hampl