fork download
  1. #Part 2
  2.  
  3. class CartesianProduct
  4. include Enumerable
  5.  
  6. def initialize(p1, p2)
  7. @first = p1
  8. @second = p2
  9. end
  10.  
  11. def each
  12. @first.each do |part1|
  13. @second.each do |part2|
  14. yield[part1, part2]
  15. end
  16. end
  17. end
  18. end
  19.  
  20. c = CartesianProduct.new([:a,:b], [4,5])
  21. c.each { |elt| puts elt.inspect }
  22. # [:a, 4]
  23. # [:a, 5]
  24. # [:b, 4]
  25. # [:b, 5]
  26.  
  27. c = CartesianProduct.new([:a,:b], [])
  28. c.each { |elt| puts elt.inspect }
  29. # (nothing printed since Cartesian product
  30. # of anything with an empty collection is empty)
Runtime error #stdin #stdout 0s 4760KB
stdin
Standard input is empty
stdout
nil