Skip to content

Instantly share code, notes, and snippets.

@jamesmartin
Created March 9, 2012 06:22
Show Gist options
  • Save jamesmartin/2005327 to your computer and use it in GitHub Desktop.
Save jamesmartin/2005327 to your computer and use it in GitHub Desktop.
The Ruby Enumerable#zip method (matrix transform), in Ruby
require 'minitest/autorun'
class Array
def zzzip(*args)
results = []
i = 0
each do |ary_element|
zipped_entry = args.inject([ary_element]) do |memo, element|
memo << element[i]
end
results << zipped_entry
i += 1
end
results
end
end
class TestZzzip < MiniTest::Unit::TestCase
def setup
@a = ['Low', 'Medium', 'High']
@b = [{'a' => 1}, {'b' => 2}, {'c' => 3}]
end
def test_zipping_no_args
assert_equal @a.zip, @a.zzzip
end
def test_zipping_equal_number_of_args
assert_equal @a.zip([7,8,9]), @a.zzzip([7,8,9])
end
def test_zipping_more_exotic_arrays
assert_equal @a.zip(@b), @a.zzzip(@b)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment