How can I create a matrix in ruby?

1

I have a question about ruby, I still can not figure out how to use a matrix. In java I can do this:

int matriz[][] = new int[3][3]

and to get a matrix by keyboard I go through two for matrix[i][j] = dato .

Now I want to implement the same in ruby, which I can not understand, because there is a Matrix class but I do not know how to use it. I know that in ruby I can do this too:

arreglo=[[1,2,4],[2,3,4],[7,8,9]]

but I do not understand how I could fill it in a for from the keyboard, some help?

    
asked by Jose 19.02.2017 в 18:03
source

1 answer

4

First of all, unlike other languages, in Ruby you do not need to define the size of an array to start entering elements.

You can create an array:

array = []  #=> []

And enter items with Array#push as if from a generic container will be:

array.push(1)  #=> [1]

Or even with Array#[]= :

array[2] = 3  #=> [1, nil, 3]

Having this clear, you can also create an array with the Array::new method The advantage is that this method receives two optional parameters: the first is the size of the array and the second is the element with which each element will be filled by default.

This way you can an empty multidimensional array:

matrix = Array.new(3, [])  #=> [[], [], []]

Now I just need to fill it out. This process can be done in many ways, but a way very similar to how it could be used in other languages such as Java, would be like this:

for i in 0...3
  for j in 0...3
    print("matrix[#{i}][#{j}]: ")
    matrix[i][j] = gets.to_i
  end
end

Greetings.

    
answered by 19.02.2017 / 19:54
source