Class: Virtop::Table
- Inherits:
-
Object
- Object
- Virtop::Table
- Defined in:
- lib/virtop/table.rb
Overview
Represents a table. Important for column width correction and sorting of rows.
Instance Method Summary collapse
-
#add_row(*args) ⇒ Object
Adds a row to the table.
-
#format ⇒ Object
Converts the whole table as array of strings, which are fancy formatted (mainly for good column widths).
-
#initialize(*args) ⇒ Table
constructor
Contructor gets table header strings as arguments.
-
#sort_by(col) ⇒ Object
Sorts the table by a certain column given by it’s header string or the index of the column starting at zero.
Constructor Details
#initialize(*args) ⇒ Table
Contructor gets table header strings as arguments.
4 5 6 7 8 |
# File 'lib/virtop/table.rb', line 4 def initialize(*args) @header = args @rows = [] @widths = [0] * args.size end |
Instance Method Details
#add_row(*args) ⇒ Object
Adds a row to the table. Number of arguments must equal the number of columns given by header strings on contruction.
12 13 14 15 16 17 18 |
# File 'lib/virtop/table.rb', line 12 def add_row(*args) if args.size != @header.size raise Exception.new 'Wrong column number.' end @rows.push args end |
#format ⇒ Object
Converts the whole table as array of strings, which are fancy formatted (mainly for good column widths).
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/virtop/table.rb', line 40 def format update_widths! a = [] ([@header] + @rows).each do |row| line = '' @header.size.times do |i| line += row[i].to_s.ljust(@widths[i] + 2) end a.push(line + "\n") end a end |
#sort_by(col) ⇒ Object
Sorts the table by a certain column given by it’s header string or the index of the column starting at zero.
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/virtop/table.rb', line 22 def sort_by(col) if col.class == String index = @header.index col else index = col.to_i end @rows = @rows.sort_by do |row| if block_given? yield row[index] else row[index] end end end |