Last active
October 2, 2015 06:08
-
-
Save Flushot/2187139 to your computer and use it in GitHub Desktop.
Like map, but for two lists instead of one.
This file contains 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
# | |
# Combines 2 vectors into a single vector of size av, | |
# by applying a binary operation (defined in block) | |
# on each element. | |
# | |
# Examples: | |
# map2([1,2,3], [4,5,6]) { |a,b| a*b } == [4,10,18] | |
# map2([1,2,3], [4,5] ) { |a,b| a+b } == [5,7,nil] | |
# map2([1,2], [4,5,6]) { |a,b| a+b } == [5,7] | |
# | |
def map2(av, bv, &block) | |
raise 'Argument is not an Enumerable' \ | |
if !av.kind_of?(Enumerable) || !bv.kind_of?(Enumerable) | |
result = Array.new av.size | |
av.size.times do | |
i, size = 0, av.size | |
while i < size | |
result[i] = i < bv.size ? | |
yield(av[i], bv[i]) : nil | |
i += 1 | |
end | |
end | |
result | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment