user2128702
user2128702

Reputation: 2121

How to assign value to a two-dimensional array in Ruby

I have a two-dimensional array generated like this:

two_dimensional = Array.new(3){Array.new(5, 0)}

which after two_dimensional.each {|a| p a} generates this :

[0,0,0,0,0]
[0,0,0,0,0]
[0,0,0,0,0]

I have coordinates coming like this (x,y). How can I assign (x,y) to two_dimensional ?

if I do two_dimensional[2][0] = 1 for the point: (2,0) I expect this:

[0,0,1,0,0]
[0,0,0,0,0]
[0,0,0,0,0]

but what gets generated is:

[0,0,0,0,0]
[0,0,0,0,0]
[1,0,0,0,0]

I hope you understand what I am trying to achieve.

Upvotes: 0

Views: 2719

Answers (3)

sawa
sawa

Reputation: 168081

For the particular problem, you can replace the positions of x and y such as:

two_dimensional[0][2] = 1

but that would not be a good solution for a system with a wider perspective. You are mixing up two systems: one in which an array consists of rows and another in which an array consists of columns.

You have to decide one, don't mix. Just stick to one system. If you think you would want to access the way you suggest, then have the array transposed from the beginning. Instead of:

two_dimensional = Array.new(3){Array.new(5, 0)}

do:

two_dimensional = Array.new(5){Array.new(3, 0)}

and whenever you want to display it, you can use the transpose method.

Upvotes: 0

Cary Swoveland
Cary Swoveland

Reputation: 110665

If you had a 3x3 array

a = [0,1,3]
    [4,5,6]
    [7,8,9]

that would mean

a = [[0,1,3], [4,5,6], [7,8,9]]

so if you want a[1][2]

a[1] = [4,5,6]

so

a[1][2] = 6

Recall that indexing begins at zero.

An easy way to remember is that a one-dimensional array is expressed as a row, not a column.

Upvotes: 2

Peter Alfvin
Peter Alfvin

Reputation: 29389

You've got the row and column reversed.

Upvotes: 1

Related Questions