tim_xyz tim_xyz - 15 days ago 6
Ruby Question

Convert a nested array to a matrix in Ruby?

When converting a nested array to a matrix in Ruby, the matrix ends up with an extra

[]
around the values, compared to simply creating a 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 the extra square brackets when building from an array?

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

The asterisk (*) there is called the "splat operator," and it essentially can be used to treat an array (nested_array in this case) as if it weren't an array, but rather as if its elements were individual elements/arguments.