Skip to content

Instantly share code, notes, and snippets.

@terrafied
Created May 17, 2013 20:35
Show Gist options
  • Save terrafied/5601814 to your computer and use it in GitHub Desktop.
Save terrafied/5601814 to your computer and use it in GitHub Desktop.
Safe transpose method, to avoid IndexErrors with non-rectangular multidimensional arrays
# Safe transpose method, to avoid IndexErrors with non-rectangular multidimensional arrays
# >> a = [[1,2], [3,4], [5]]
# >> puts a.transpose.inspect
# [[1, 3, 5], [2, 4, nil]]
class Array
def safe_transpose
result = []
max_size = self.max { |a,b| a.size <=> b.size }.size
max_size.times do |i|
result[i] = Array.new(self.first.size)
self.each_with_index { |r,j| result[i][j] = r[i] }
end
result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment