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
17
# File 'lib/list_to_columns/column_major.rb', line 7

def initialize(list = nil, options = nil)
  options ||= {}
  @indent   = options[:indent] || 0
  @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

#indentObject (readonly)

Returns the value of attribute indent.



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

def indent
  @indent
end

#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



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

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

#matrixObject



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

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



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

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

#number_of_rowsObject



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

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

#to_sObject



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

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