Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class String
- # reformats a list (newline separated) into columns
- def columnize(columns=2, orientation="vertical", prepend="")
- list = self.split("\n")
- sizes = []
- out = ""
- items = (list.length.to_f/columns.to_f).ceil #items per column
- orientation = (orientation[0,1].downcase == "v")
- if (orientation) then
- 0.upto(columns-1) { |col|
- 0.upto(items-1) { |row|
- item = col*items+row
- list[item] = list[item].nil? ? "" : prepend+list[item]
- sizes[col] = [sizes[col], list[item].length].max
- }
- }
- 0.upto(items-1) { |row|
- 0.upto(columns-1) { |col|
- item = col*items+row
- out = out+list[item]+" "*(((sizes[col]-list[item].length)+2))
- }
- out = out+"\n"
- }
- else
- 0.upto(columns-1) { |col|
- 0.upto(items-1) { |row|
- item = row*columns+col
- list[item] = list[item].nil? ? "" : prepend+list[item]
- sizes[col] = [sizes[col], list[item].length].max
- }
- }
- 0.upto(items-1) { |row|
- 0.upto(columns-1) { |col|
- item = row*columns+col
- out = out+list[item]+" "*(((sizes[col]-list[item].length)+2))
- }
- out = out+"\n"
- }
- end
- return out[0..-2]
- end
- end
Add Comment
Please, Sign In to add comment