Class: Primegrid::MatrixPrinter
- Inherits:
-
Object
- Object
- Primegrid::MatrixPrinter
- Defined in:
- lib/primegrid/matrix_printer.rb
Constant Summary collapse
- @@gutter_width =
Prints out an un-rolled matrix to $stdout
Example:
>> MatrixPrinter.print([1, 0, 0, 0, 1, 0, 0, 0, 1], 3) => 1 0 0 => 0 1 0 => 0 0 1
Arguments:
array: the unrolled matrix width: the number of columns in the matrix opts : a hash containing optional arrays for row and column headers e.g. { :col_header => [0, 1, 2], :row_header => [0, 1, 2] }
2
- @@h_border_char =
"-"
- @@v_border_char =
"|"
Class Method Summary collapse
- .build_matrix(array, width, opts = {}) ⇒ Object
- .maxlen_in(array) ⇒ Object
- .print(array, width, opts = {}) ⇒ Object
Class Method Details
.build_matrix(array, width, opts = {}) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/primegrid/matrix_printer.rb', line 28 def self.build_matrix(array, width, opts={}) if array.length == 0 then return "" end padding = self.maxlen_in array gutter = " " * @@gutter_width has_header = opts.has_key? :col_header has_row_header = opts.has_key? :row_header buf = [] # Add an optional header row if has_header header_sep = "-" padding = [padding, self.maxlen_in(opts[:col_header])].max header_str = opts[:col_header].map{|h| h.to_s.rjust(padding)}.join(gutter) buf.push "#{header_str}" buf.push "#{@@h_border_char * header_str.length}" end # Build the body of the matrix line = "" array.each_with_index do |p, i| line = "#{line}#{p.to_s.rjust(padding)}#{gutter}" if (i+1) % width == 0 buf.push "#{line.rstrip}" line = "" end end # Add row headers if has_row_header padding = self.maxlen_in(opts[:row_header]) padded_headers = opts[:row_header].map{|r| r.to_s.rjust(padding)} offset = 0 if has_header offset = 2 buf[0] = "#{' ' * (padding+1)}#{buf[0]}" buf[1] = "#{' ' * (padding+1)}#{buf[1]}" end padded_headers.each_with_index do |r, i| if i + offset < buf.length buf[i + offset] = "#{r}#{@@v_border_char}#{buf[i + offset]}" end end end return buf.join("\n") end |
.maxlen_in(array) ⇒ Object
77 78 79 80 |
# File 'lib/primegrid/matrix_printer.rb', line 77 def self.maxlen_in(array) as_lengths = array.map {|x| x.to_s.length} return as_lengths.max end |
.print(array, width, opts = {}) ⇒ Object
21 22 23 24 25 26 |
# File 'lib/primegrid/matrix_printer.rb', line 21 def self.print(array, width, opts={}) matrix = self.build_matrix(array, width, opts) if !matrix.empty? $stdout.puts matrix end end |