Skip to content

Instantly share code, notes, and snippets.

@moonmaster9000
Created April 11, 2010 13:14
Show Gist options
  • Save moonmaster9000/362705 to your computer and use it in GitHub Desktop.
Save moonmaster9000/362705 to your computer and use it in GitHub Desktop.
require 'enumerator'
class Array
def column_sort(num_columns, &block)
new_array = block ? sort(&block) : self.dup
extras = new_array.length % num_columns
new_length = extras == 0 ? new_array.length : new_array.length + num_columns - extras
new_array.pad(new_length).slices(num_columns).transpose.flatten
end
def pad(new_length)
if new_length > length
self + ([nil] * (new_length - length))
else
self.dup
end
end
def slices(num_slices)
array_of_slices = []
each_slice(length / num_slices) { |s| array_of_slices << s }
array_of_slices
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment