简体   繁体   中英

Ruby, multidimensional array push error

  array = [[]]
  for level in 0..counter-1
    for line in 0..counter-1
      array[level].push(rectangle[x+level][y+line])
    end
  end

I get this error NoMethodError: undefined method `push' for nil:NilClass

I want to find all squares inside a rectangle, but when I try to save that square in to custom array I get an error.

array[level].push(rectangle[x+level][y+line])

all I want to do here to generate a square like for example array[[3, 4],[5, 2]] which would be

3 4 5 2 . the problem is that array[0].push(rectangle[x+level][y+line]) with number instead of variable is working, but with variable 'level' it gives me error, however if i use constant number i cannot generate multi level array.

any help?

The problem is that array only has one element, that's why it was working for level = 0. You can easily fix it like this:

 array = []
 for level in 0..counter-1
   array.push []
   for line in 0..counter-1
     array[level].push(rectangle[x+level][y+line])
   end
 end

found a solution

  2darray = [[]]
  i=0
  for level in 0..counter-1
    array = []
    for line in 0..counter-1
      array.push(rectangle[x+level][y+line])
    end
    2darray.push(array)

generate 1d array and append it to 2d array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM