1 require ‘matrix‘ 2 3 class Matrix 4 def to_pretty_s 5 s = "" 6 i = 0 7 while i < self.column_size 8 s += "\n" if i != 0 9 j = 0 10 while j < self.row_size 11 s += ‘ ‘ if j != 0 12 s += self.element(i, j).to_s 13 j += 1 14 end 15 i += 1 16 end 17 s 18 end 19 20 def to_readable 21 maximal_length = 15 22 column_counter = 0 23 columns_arrays = [] 24 while column_counter < self.column_size 25 maximum_length = 0 26 self.column(column_counter).each do |column_element|# Get maximal size 27 length = column_element.to_s.size 28 if length > maximal_length 29 maximum_length = length 30 end 31 end # now we‘ve got the maximum size 32 column_array = [] 33 self.column(column_counter).each do |column_element| # Add needed spaces to equalize each column 34 element_string = column_element.to_s 35 element_size = element_string.size 36 space_needed = maximal_length - element_size +1 37 if space_needed > 0 38 space_needed.times {element_string.prepend " "} 39 if column_counter == 0 40 element_string.prepend "[" 41 else 42 element_string.prepend "," 43 end 44 end 45 column_array << element_string 46 end 47 columns_arrays << column_array # Now columns contains equal size strings 48 column_counter += 1 49 end 50 row_counter = 0 51 while row_counter < self.row_size 52 columns_arrays.each do |column| 53 element = column[row_counter] 54 print element #Each column yield the correspondant row in order 55 end 56 print "]\n" 57 row_counter += 1 58 end 59 end 60 61 def my_print 62 matrix = self.to_a 63 field_size = matrix.flatten.collect{|i|i.to_s.size}.max 64 matrix.each do |row| 65 puts (row.collect{|i| ‘ ‘ * (field_size - i.to_s.size) + i.to_s}).join(‘ ‘) 66 end 67 end 68 end 69 70 m = Matrix[[12345678910, 333, 22.111], [3, 0.12345678, 3], [-333, 3, 4]] 71 72 puts m # same as puts m.to_s 73 puts m.to_pretty_s 74 p m.to_pretty_s 75 m.to_readable 76 m.my_print 77 # Matrix[[12345678910, 333, 22.111], [3, 0.12345678, 3], [-333, 3, 4]] 78 # 12345678910 333 22.111 79 # 3 0.12345678 3 80 # -333 3 4 81 # "12345678910 333 22.111\n3 0.12345678 3\n-333 3 4" 82 # [ 12345678910, 333, 22.111] 83 # [ 3, 0.12345678, 3] 84 # [ -333, 3, 4] 85 # 12345678910 333 22.111 86 # 3 0.12345678 3 87 # -333 3 4
时间: 2024-12-17 14:03:51