• Our software update is now concluded. You will need to reset your password to log in. In order to do this, you will have to click "Log in" in the top right corner and then "Forgot your password?".
  • Welcome to PokéCommunity! Register now and join one of the best fan communities on the 'net to talk Pokémon and more! We are not affiliated with The Pokémon Company or Nintendo.

Multidimensional Arrays and the Push Function

18
Posts
7
Years
  • Hello, I've been having trouble trying to push variables in 2 dimensional arrays. I don't even know if this is possible.

    The first thing I do is initialize the array like so:
    Code:
    array2=Array.new(3){Array.new}

    Next, I have two other variables, for example:
    Code:
    var1=3
    var2=rand(10)

    So what I'm trying to do is to push the array that is inside the array.
    Code:
    for x in 0...var1
       for i in 0...var2
          array2[x].push[i]=rand(50)
       end
    end

    However, this isn't working. Can you use the push function in 2 dimensional arrays? Or is the problem elsewhere?
     
    1,224
    Posts
    10
    Years
  • push is a method to act on an array, you've got your syntax wrong

    Code:
    for x in 0...var1
       for i in 0...var2
          array2[x][i].push(rand(50))
       end
    end

    However, this is still wrong. You've only got a two level array here
    (looks like)
    Code:
    [
        [1,2,3,4,5],
        [1,2,3,4,7],
        [1,2,3,4,5]
    ]
    So your original code is also trying to use the push method on a member of the sub-array, not the array itself

    Code:
    for x in 0...array2.size  #var1 is uneccessary, since array2's size may change
        var2.times {array2[x].push(rand(50)) }
    end
     
    18
    Posts
    7
    Years
  • push is a method to act on an array, you've got your syntax wrong

    Code:
    for x in 0...var1
       for i in 0...var2
          array2[x][i].push(rand(50))
       end
    end

    However, this is still wrong. You've only got a two level array here
    (looks like)
    Code:
    [
        [1,2,3,4,5],
        [1,2,3,4,7],
        [1,2,3,4,5]
    ]
    So your original code is also trying to use the push method on a member of the sub-array, not the array itself

    Code:
    for x in 0...array2.size  #var1 is uneccessary, since array2's size may change
        var2.times {array2[x].push(rand(50)) }
    end

    Ah, I see. I've been running a few tests on some Ruby editors and yeah, I see that now. Thanks for clearing that up!
     

    MysteriousUser94

    Guest
    0
    Posts
    You can also init your array like this :
    Code:
    array2 = Array.new(3) { Array.new(rand(10)) { rand(50) } }

    PS : You can get the current index of the item while initializing the array like this :
    Code:
    array2 = Array.new(3) { |index_x| Array.new(rand(10)) { |index_y| rand(50) } }
    (If you want to put something else than random numbers)
     
    Back
    Top