Created
June 14, 2012 18:28
-
-
Save pwightman/2931995 to your computer and use it in GitHub Desktop.
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
class CartesianProduct | |
include Enumerable | |
def initialize a, b | |
@a = a | |
@b = b | |
end | |
# Every method has an implied block that is sent into it, it does NOT need to be | |
# specified as a parameter. | |
def each | |
# Just your average doubly-nested loop | |
@a.each do |a_el| | |
@b.each do |b_el| | |
# yield will call whatever block gets passed into this method, passing | |
# an array of the two elements as a parameter. block_given? returns false | |
# if no block was passed to this method. Trying to call yield when no block | |
# was passed to the method results in an exception being thrown. | |
yield [a_el, b_el] if block_given? | |
end | |
end | |
end | |
end | |
c = CartesianProduct.new([:a,:b], [4,5]) | |
c.each { |el| puts el.inspect } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment