Skip to content

Instantly share code, notes, and snippets.

@davidlee
Created May 27, 2010 04:39
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 davidlee/415464 to your computer and use it in GitHub Desktop.
Save davidlee/415464 to your computer and use it in GitHub Desktop.
class Array
def columns(padding=1)
col_sizes = inject([]) do |sizes, row|
row.each_with_index.each do |col, i|
sizes[i] = [sizes[i], col.to_s.length].compact.max
end
sizes
end
out = []
each do |row|
out << row.each_with_index.map {|col, i|
col.to_s.ljust col_sizes[i]
}.join(' ' * padding)
end
out
end
def columnize(padding=1, cr="\n")
columns(padding).join(cr)
end
end
irb(main):747:0* sample = 10.times.map do
irb(main):748:1* 5.times.map { '#' * rand(10) }
irb(main):749:1> end
=> [["#########", "#", "#", "###", "#"], ["########", "####", "###", "#######", "#######"], ["#", "##", "#####", "######", ""], ["", "#", "#", "#######", "#########"], ["###", "#######", "#####", "######", "####"], ["###", "###", "########", "#####", "######"], ["#########", "########", "#####", "##", "#######"], ["###", "#####", "########", "#", "#########"], ["######", "###", "######", "#####", "####"], ["##", "#####", "##", "#####", "###"]]
irb(main):750:0>
irb(main):751:0* puts sample.columnize
######### # # ### #
######## #### ### ####### #######
# ## ##### ######
# # ####### #########
### ####### ##### ###### ####
### ### ######## ##### ######
######### ######## ##### ## #######
### ##### ######## # #########
###### ### ###### ##### ####
## ##### ## ##### ###
=> nil
irb(main):752:0> puts
=> nil
irb(main):753:0> puts sample.columnize(2)
######### # # ### #
######## #### ### ####### #######
# ## ##### ######
# # ####### #########
### ####### ##### ###### ####
### ### ######## ##### ######
######### ######## ##### ## #######
### ##### ######## # #########
###### ### ###### ##### ####
## ##### ## ##### ###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment