Convert nested array to matrix in Ruby?

When converting a nested array into a matrix in Ruby, the matrix ends up adding [] around the values, compared to just creating the matrix from scratch.

 > require 'matrix' > matrix1 = Matrix[[1,2,3],[4,5,6],[7,8,9]] > p matrix1 

=> Matrix [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

 > nested_array = [[1,2,3],[4,5,6],[7,8,9]] > matrix2 = Matrix[nested_array] > p matrix2 

=> Matrix [[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]

Is there a way to avoid extra square brackets when creating from an array?

+5
source share
1 answer
 matrix2 = Matrix[*nested_array] p matrix2 => Matrix[[1, 2, 3], [4, 5, 6], [7, 8, 9]] 

An asterisk ( * ) is called the "splat operator" and can essentially be used to process the array ( nested_array in this case), as if it were not an array, but rather as if its elements were separate elements / arguments.

+9
source

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


All Articles