標籤:
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 = 010 while j < self.row_size11 s += ‘ ‘ if j != 012 s += self.element(i, j).to_s13 j += 114 end15 i += 116 end17 s18 end19 20 def to_readable21 maximal_length = 1522 column_counter = 023 columns_arrays = []24 while column_counter < self.column_size25 maximum_length = 026 self.column(column_counter).each do |column_element|# Get maximal size27 length = column_element.to_s.size28 if length > maximal_length29 maximum_length = length30 end31 end # now we‘ve got the maximum size32 column_array = []33 self.column(column_counter).each do |column_element| # Add needed spaces to equalize each column34 element_string = column_element.to_s35 element_size = element_string.size36 space_needed = maximal_length - element_size +137 if space_needed > 038 space_needed.times {element_string.prepend " "}39 if column_counter == 040 element_string.prepend "["41 else42 element_string.prepend ","43 end 44 end45 column_array << element_string46 end47 columns_arrays << column_array # Now columns contains equal size strings48 column_counter += 149 end50 row_counter = 051 while row_counter < self.row_size52 columns_arrays.each do |column|53 element = column[row_counter]54 print element #Each column yield the correspondant row in order55 end56 print "]\n"57 row_counter += 158 end59 end60 61 def my_print62 matrix = self.to_a63 field_size = matrix.flatten.collect{|i|i.to_s.size}.max64 matrix.each do |row|65 puts (row.collect{|i| ‘ ‘ * (field_size - i.to_s.size) + i.to_s}).join(‘ ‘) 66 end67 end68 end69 70 m = Matrix[[12345678910, 333, 22.111], [3, 0.12345678, 3], [-333, 3, 4]]71 72 puts m # same as puts m.to_s73 puts m.to_pretty_s74 p m.to_pretty_s75 m.to_readable76 m.my_print77 # Matrix[[12345678910, 333, 22.111], [3, 0.12345678, 3], [-333, 3, 4]]78 # 12345678910 333 22.11179 # 3 0.12345678 380 # -333 3 481 # "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.11186 # 3 0.12345678 387 # -333 3 4
ruby Matrix 輸出 格式化