Dynamically creating a multidimensional array in Ruby

I am trying to build a multidimensional array dynamically. I want, 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 an error: NoMethodError: undefined method `<<<for nil: NilClass. I can make it work by setting the array as

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

and it works fine, but in my actual use I will not know how many arrays will be required in advance. Is there a better way to do this? Thanks

+4
source share
3 answers

There is no need for an index variable as you use. Just add each array to the 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"]] 
+6
source

Do not 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 even better:

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

Here is a simple example if you know the size of the array you are creating.
@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 
Result

will be @TwoDArray = [[1,2,3]. [3,4,5], [6,7,8]]

0
source

Source: https://habr.com/ru/post/1309214/


All Articles