require 'matrix' class Matrix
def to_pretty_s
s = ""
i = 0
while i < self.column_size
s += "\n" if i != 0
j = 0
while j < self.row_size
s += ' ' if j != 0
s += self.element(i, j).to_s
j += 1
end
i += 1
end
s
end def to_readable
maximal_length = 15
column_counter = 0
columns_arrays = []
while column_counter < self.column_size
maximum_length = 0
self.column(column_counter).each do |column_element|# Get maximal size
length = column_element.to_s.size
if length > maximal_length
maximum_length = length
end
end # now we've got the maximum size
column_array = []
self.column(column_counter).each do |column_element| # Add needed spaces to equalize each column
element_string = column_element.to_s
element_size = element_string.size
space_needed = maximal_length - element_size +1
if space_needed > 0
space_needed.times {element_string.prepend " "}
if column_counter == 0
element_string.prepend "["
else
element_string.prepend ","
end
end
column_array << element_string
end
columns_arrays << column_array # Now columns contains equal size strings
column_counter += 1
end
row_counter = 0
while row_counter < self.row_size
columns_arrays.each do |column|
element = column[row_counter]
print element #Each column yield the correspondant row in order
end
print "]\n"
row_counter += 1
end
end def my_print
matrix = self.to_a
field_size = matrix.flatten.collect{|i|i.to_s.size}.max
matrix.each do |row|
puts (row.collect{|i| ' ' * (field_size - i.to_s.size) + i.to_s}).join(' ')
end
end
end m = Matrix[[12345678910, 333, 22.111], [3, 0.12345678, 3], [-333, 3, 4]] puts m # same as puts m.to_s
puts m.to_pretty_s
p m.to_pretty_s
m.to_readable
m.my_print
# Matrix[[12345678910, 333, 22.111], [3, 0.12345678, 3], [-333, 3, 4]]
# 12345678910 333 22.111
# 3 0.12345678 3
# -333 3 4
# "12345678910 333 22.111\n3 0.12345678 3\n-333 3 4"
# [ 12345678910, 333, 22.111]
# [ 3, 0.12345678, 3]
# [ -333, 3, 4]
# 12345678910 333 22.111
# 3 0.12345678 3
# -333 3 4