Skip to content

Instantly share code, notes, and snippets.

@forsaken1
Last active September 29, 2015 00:24
Show Gist options
  • Save forsaken1/7e31ed7a2c6364f0fb9a to your computer and use it in GitHub Desktop.
Save forsaken1/7e31ed7a2c6364f0fb9a to your computer and use it in GitHub Desktop.
Ruby monkey patching
class Array
# [1, 2, 3, 4, 5, 6, 7, 8].to_columns 1, 2, 3, 2 => [[1], [2, 3], [4, 5, 6], [7, 8]]
def to_columns *column_counts
return [] if self.empty?
result, start_iterator, end_iterator = [], 0, 0
column_counts.each do |column_count|
end_iterator = start_iterator + column_count
cut = self[start_iterator...end_iterator]
result << cut unless cut.nil?
start_iterator += column_count
end
result
end
# [1, 2, 3, 4, 5, 6, 7, 8, 9].to_columns_in_lines 3 => [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
def to_columns_in_lines column_count
return [] if self.empty?
return self if column_count == 0
result = Array.new(column_count) { [] }
self.each_with_index { |item, index| result[index % column_count] << item }
result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment