9

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?

1 Answer 1

15
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.