class MDTable

Constants

VERSION

Public Class Methods

convert(rows) click to toggle source

convert 2D array to md table array

rows - array of array

Examples:

MDTable.convert [[1,2,3], ['x', 'x', 'x']]
# => ['1 | 2 | 3',
      '- | - | -',
      'x | x | x']

Returns an array of string as a markdown table

# File lib/mdtable.rb, line 17
def self.convert(rows)
  rows = rows.map {|row| row.map(&:to_s) }
  new(rows).to_md
end
new(rows) click to toggle source
# File lib/mdtable.rb, line 22
def initialize rows
  @rows = rows
end

Public Instance Methods

col_lengths() click to toggle source
# File lib/mdtable.rb, line 32
def col_lengths
  @col_lengths ||= 0.upto(@rows.first.size - 1).map {|i|
    @rows.map {|r| r[i].length }.max
  }
end
table() click to toggle source
# File lib/mdtable.rb, line 38
def table
  @table ||= @rows.dup.insert(1, col_lengths.map {|l| '-' * l })
end
to_md() click to toggle source
# File lib/mdtable.rb, line 26
def to_md
  table.map {|row|
    row.each_with_index.map {|item, i| item.ljust(col_lengths[i])}.join ' | '
  }
end