Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a nested array to a matrix in Ruby?

Tags:

ruby

matrix

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?

like image 772
tim_xyz Avatar asked Nov 23 '16 03:11

tim_xyz


1 Answers

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.

like image 102
David Runger Avatar answered Oct 31 '22 20:10

David Runger