Skip to content

Instantly share code, notes, and snippets.

@pwightman
Created June 14, 2012 18:28
Show Gist options
  • Save pwightman/2931995 to your computer and use it in GitHub Desktop.
Save pwightman/2931995 to your computer and use it in GitHub Desktop.
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