Print in a Frame

tags: linear-scan dynamic-spacing array-traversal traverse-sequence

Write a function that takes a list of strings an prints them, one per line, in a rectangular frame. For example the list [“Hello”, “World”, “in”, “a”, “frame”] gets printed as:

*********
* Hello *
* World *
* in    *
* a     *
* frame *
*********

The first attempt results in the right side * not aligning properly:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def frame(a)
  biggest =  a.max_by{|x| x.size }
  frame_width = biggest.size.to_i + 5

  p "*" * frame_width
  
  for i in (0..a.size-1)
    p "* #{a[i]} *"
  end
  
  p "*" * frame_width
end

a = ["Hello", "World", "in", "a", "frame"]
frame(a)

Final version:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
def frame(a)
  biggest =  a.max_by{|x| x.size }
  frame_width = biggest.size.to_i + 5

  p "*" * frame_width
  
  for i in (0..a.size-1)
    spaces = frame_width - a[i].size - 2
    print "* #{a[i]}"
    print " " * spaces
    puts "*"
  end
  
  p "*" * frame_width
end

a = ["Hello", "World", "in", "a", "frame"]
frame(a)

In the beginning a * and space is printed so to make the last * print on the right side, 2 must be subtracted to calculate the spaces to print after the word.