Module: LsTable

Defined in:
lib/ls_table.rb

Overview


File : ls_table.rb Authors : ccmywish <[email protected]> Created on : <2022-03-23> Last modified : <2022-04-29>

ls_table:

List table

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
"0.1.3"

Class Method Summary collapse

Class Method Details

.ls(arr, cell_len: 9, cell_num: 8) ⇒ Object



18
19
20
21
22
23
24
25
26
27
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
# File 'lib/ls_table.rb', line 18

def LsTable.ls(arr, cell_len: 9, cell_num: 8)

  result_lines = []

  return if arr.empty?

  cell_delimiter = 1

  one_line_cap = (cell_len + cell_delimiter) * cell_num  # == 80
  
  sentry = []
  cell_num.times do |n|
    sentry << (n + 1) * (cell_len + cell_delimiter)
  end
  # [10, 20, 30, 40, 50, 60, 70, 80]
  
  si = 0

  line = ""
  #p arr
  arr.each do |e|

    next if e.length > one_line_cap

    while line.length + e.length >= sentry[si]
      si += 1

      if si > (sentry.size - 1)  
        yield line if block_given?
        result_lines << line
        line = "" ; si = 0
        redo
      end
    end

    line << e
    line = line.ljust(sentry[si])

    if line.size == one_line_cap  
      yield line if block_given?
      result_lines << line
      line = "" ; si = 0
      next
    end

  end

  # Two situations:
  #   1. all cells done already (line empty)
  #   2. rest cells not occupy one line (line not empty)
  if !line.empty?
    # All cells done
    yield line if block_given?
    result_lines << line
  end
  result_lines
end