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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With