Skip to content

Instantly share code, notes, and snippets.

@aalin
Created November 29, 2016 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aalin/bf147876b2cf068a0510323dfb86401a to your computer and use it in GitHub Desktop.
Save aalin/bf147876b2cf068a0510323dfb86401a to your computer and use it in GitHub Desktop.
Format files in a table like ls
require 'io/console'
require 'pp'
files = Dir["*"].sort
MAX_COLUMNS = 9
MAX_COLUMNS.downto(1) do |i|
columns = files.each_slice(i).map { |x| Array.new(i) { |n| x[n] } }
rows = columns.transpose
space = 2
column_widths = columns.map { |values| values.map(&:to_s).map(&:size).max + space }
screen_width = $stdin.winsize[1]
total_width = column_widths.inject(0, :+) # sum
if total_width < screen_width
rows.each_with_index do |values, y|
values.each_with_index do |value, x|
width = column_widths[x] || 0
print value.to_s.ljust(width)
end
puts
end
end
puts
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment