Skip to content

Instantly share code, notes, and snippets.

@makaroni4
Created April 6, 2012 11:04
Show Gist options
  • Save makaroni4/2318887 to your computer and use it in GitHub Desktop.
Save makaroni4/2318887 to your computer and use it in GitHub Desktop.
Implementation of Array#transpose
require 'test/unit'
include Test::Unit::Assertions
class Array
def transpose
return [] if empty?
a = Array.new(self.first.size) {[]}
each do |e|
begin
e.each_index { |j| a[j].push e[j] || nil }
rescue NoMethodError
raise "Element size differs: #{e.size} ? #{a.size}"
end
end
a
end
end
assert_equal [[1, 2, 3], [:a, :b, :c]].transpose, [[1, :a], [2, :b], [3, :c]]
assert_equal [[1,2], [3,4], [5,6]].transpose, [[1, 3, 5], [2, 4, 6]]
assert_equal [].transpose, []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment