Created
May 17, 2013 20:35
-
-
Save terrafied/5601814 to your computer and use it in GitHub Desktop.
Safe transpose method, to avoid IndexErrors with non-rectangular multidimensional arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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