Created
March 9, 2012 06:22
-
-
Save jamesmartin/2005327 to your computer and use it in GitHub Desktop.
The Ruby Enumerable#zip method (matrix transform), in Ruby
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
| 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