Skip to content

Instantly share code, notes, and snippets.

@arnab
Created December 18, 2009 19:48
Show Gist options
  • Save arnab/259715 to your computer and use it in GitHub Desktop.
Save arnab/259715 to your computer and use it in GitHub Desktop.
def columnize(arr, columns)
size_in_group = arr.size / columns
if arr.size % columns != 0
size_in_group += 1
end
arr_grouped = [ ]
size_in_group.times do |m|
columns.times do |i|
arr_grouped[i] ||= []
arr_grouped[i] << arr[m * columns + i]
end
end
arr_grouped
end
# Examples:
require "pp"
# Input: a..z, columns: 2
# call:
pp columnize(('a'..'z').to_a, 2)
# Output:
[
["a", "c", "e", "g", "i", "k", "m", "o", "q", "s", "u", "w", "y"],
["b", "d", "f", "h", "j", "l", "n", "p", "r", "t", "v", "x", "z"]
]
# Input: a..z, columns: 3
# call:
pp columnize(('a'..'z').to_a, 3)
# Output:
[
["a", "d", "g", "j", "m", "p", "s", "v", "y"],
["b", "e", "h", "k", "n", "q", "t", "w", "z"],
["c", "f", "i", "l", "o", "r", "u", "x", nil]
]
# Note that the last elem in the 3rd array is nil
# Input: a..z, columns: 3
# call:
pp columnize(('a'..'x').to_a, 3)
# Output:
[
["a", "d", "g", "j", "m", "p", "s", "v"],
["b", "e", "h", "k", "n", "q", "t", "w"],
["c", "f", "i", "l", "o", "r", "u", "x"]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment