Skip to content

Instantly share code, notes, and snippets.

@njh
Last active July 24, 2024 00:07
Show Gist options
  • Save njh/f85c65591f66dd4256dd75fe9100970d to your computer and use it in GitHub Desktop.
Save njh/f85c65591f66dd4256dd75fe9100970d to your computer and use it in GitHub Desktop.
Ruby function to display an array of strings as columns on a text terminal
#!/usr/bin/env ruby
#
# Ruby function to display an array of strings
# as columns on a text terminal.
#
# Author: Nicholas Humfrey
# License: https://unlicense.org/
#
require 'io/console'
def format_as_columns(strings, column_count, column_width = nil)
per_column = (strings.count.to_f / column_count).ceil
if column_width.nil?
height, width = IO.console.winsize
column_width = (width.to_f / column_count).floor
end
result = []
(0...per_column).each do |r|
row = ''
(0...column_count).each do |c|
index = (c * per_column) + r
if strings[index].nil?
item = ''
else
item = strings[index]
end
row += item.ljust(column_width)
end
result << row
end
return result
end
strings = <<~END
1: One
2: Two
3: Three
4: Four
5: Five
6: Six
7: Seven
8: Eight
9: Nine
10: Ten
11: Eleven
12: Twelve
13: Thirteen
14: Fourteen
15: Fifthteen
16: Sixteen
17: Seventeen
18: Eighteen
19: Nineteen
20: Twenty
END
.split("\n")
puts format_as_columns(strings, 3).join("\n")
# Result:
#
# 1: One 8: Eight 15: Fifthteen
# 2: Two 9: Nine 16: Sixteen
# 3: Three 10: Ten 17: Seventeen
# 4: Four 11: Eleven 18: Eighteen
# 5: Five 12: Twelve 19: Nineteen
# 6: Six 13: Thirteen 20: Twenty
# 7: Seven 14: Fourteen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment