Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a readable Matrix in Ruby

Tags:

ruby

matrix

Is there a built in way of printing a readable matrix in Ruby?

For example

require 'matrix'
m1 = Matrix[[1,2], [3,4]]
print m1

and have it show

=> 1 2
   3 4

in the REPL instead of:

=> Matrix[[1,2][3,4]]

The Ruby Docs for matrix make it look like that's what should show happen, but that's not what I'm seeing. I know that it would be trivial to write a function to do this, but if there is a 'right' way I'd rather learn!

like image 883
vpiTriumph Avatar asked Apr 29 '12 05:04

vpiTriumph


1 Answers

You could convert it to an array:

m1.to_a.each {|r| puts r.inspect}

=> [1, 2]
   [3, 4]

EDIT:

Here is a "point free" version:

puts m1.to_a.map(&:inspect)
like image 158
seph Avatar answered Dec 11 '22 21:12

seph