Class: ListToColumns::ColumnMajor

Inherits:
Object
  • Object
show all
Defined in:
lib/list_to_columns/column_major.rb

Overview

Columnar list that is column major order; that is the order is top->bottom, then right->left.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(list = nil, options = nil) ⇒ ColumnMajor

Returns a new instance of ColumnMajor.



7
8
9
10
11
12
13
14
15
16
# File 'lib/list_to_columns/column_major.rb', line 7

def initialize(list = nil, options = nil)
  options ||= {}
  @width    = options[:width] || 78
  @space    = options[:space] || 2
  @strings  = Array(list).map(&:to_s)
  return if @strings.empty?

  # Pad out list so it is rectangular.
  @strings[number_of_columns * number_of_rows - 1] ||= nil
end

Instance Attribute Details

#spaceObject (readonly)

Returns the value of attribute space.



5
6
7
# File 'lib/list_to_columns/column_major.rb', line 5

def space
  @space
end

#widthObject (readonly)

Returns the value of attribute width.



5
6
7
# File 'lib/list_to_columns/column_major.rb', line 5

def width
  @width
end

Instance Method Details

#longest_string_lengthObject



18
19
20
# File 'lib/list_to_columns/column_major.rb', line 18

def longest_string_length
  @longest_string_length ||= @strings.map(&:length).max || 0
end

#matrixObject



32
33
34
35
36
37
38
39
40
41
# File 'lib/list_to_columns/column_major.rb', line 32

def matrix
  return [].freeze if @strings.empty?
  @matrix ||= @strings
    .each_slice(number_of_rows)
    .to_a
    .transpose
    .map(&:compact)
    .map(&:freeze)
    .freeze
end

#number_of_columnsObject



22
23
24
25
# File 'lib/list_to_columns/column_major.rb', line 22

def number_of_columns
  return 0 if @strings.empty?
  @number_of_columns ||= (width + space) / (longest_string_length + space)
end

#number_of_rowsObject



27
28
29
30
# File 'lib/list_to_columns/column_major.rb', line 27

def number_of_rows
  return 0 if @strings.empty?
  @number_of_rows ||= (@strings.length.to_f / number_of_columns).ceil
end

#to_sObject



43
44
45
46
47
48
# File 'lib/list_to_columns/column_major.rb', line 43

def to_s
  matrix
    .map { |r| r.map { |s| pad s }.join(' ' * space) }
    .map(&:rstrip)
    .join("\n")
end